Leetcod-反转链表

Posted ybxw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcod-反转链表相关的知识,希望对你有一定的参考价值。

206.逆转链表
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
方法一:迭代
技术图片
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        pre, cur = None, head
        while cur:
                pre, cur, cur.next = cur, cur.next, pre
        return pre 
iterative

方法二:递归
技术图片
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        p = self.reverseList(head.next)
        head.next.next = head
        head.next=None
        return p
recursive

 

24.两两交换链表
Given 1->2->3->4, you should return the list as 2->1->4->3.
技术图片
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        pre,pre.next = self,head
        while pre.next and pre.next.next:
            a = pre.next
            b = a.next
            a,b.next,b = b,a,b.next
            pre = a 
        return self.next
iterative

技术图片

技术图片

 

 技术图片
 
技术图片
 
141.回环链表
Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node.

方法一:设置时间暴力循环
方法二:判断是否添加过该元素
技术图片
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        l = []
        while head != None:
            if head.val in l:
                return True
            l.append(head)
            head=head.next
        return False       
添加进列表
方法三:双步运行
技术图片
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        fir = sec =head
        while fir and sec and sec.next:
           fir = fir.next
           sec = sec.next.next
           if fir == sec:
                return True
        return False     
双步
 
 
 

以上是关于Leetcod-反转链表的主要内容,如果未能解决你的问题,请参考以下文章

三行代码解反转链表

用队列实现栈

解题报告力扣 第 268 场周赛

如何链表反转

反转链表

c语言,链表的反转,请写出代码,并讲解下,谢了!!!!!