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
方法二:递归
# 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
24.两两交换链表
Given1->2->3->4
, you should return the list as2->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
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-反转链表的主要内容,如果未能解决你的问题,请参考以下文章