链表第二天
Leetcode 24:Swap Nodes in Pairs
错误代码 非常重要
cur=tmp is Shallow Copy with same memory chunk and address!!!
So, changing cur is changing tmp, which will cause Time Limit Exceeded problem
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
# split as small task: swap 1>2 as 2>1
dummynode = ListNode(next=head)
cur = dummynode
while cur.next and cur.next.next:
tmp = cur
cur.next = tmp.next.next
cur.next.next = tmp.next
# link to the next one problem
cur.next.next.next = tmp.next.next.next
cur = cur.next.next
return dummynode.next
Modified Version:
# split as small task: swap 1>2 as 2>1
dummynode = ListNode(next=head)
first = dummynode
while first.next and first.next.next:
second = first.next
third = first.next.next
forth = first.next.next.next
first.next = third
first.next.next = second
first.next.next.next = forth
first=first.next.next
return dummynode.next
Leetcode 19 Remove Nth Node From End of List
尽量别用head, 会随时改变链表, 最好每次都给头节点 dummyhead
(同样的问题)
cur = ListNode(next=head)
dummy = cur
while n>0 and dummy:
dummy = dummy.next
n-=1
dummy = dummy.next
dummy2 = cur
while dummy:
dummy = dummy.next
dummy2 = dummy2.next
dummy2.next = dummy2.next.next
return cur.next
Leetcode 142
快慢指针判断循环
# first initiate two pointers
dummy = ListNode(next = head)
fast = dummy.next #fast
slow = dummy.next #slow
# if fast can break--> no cysle; if they have a cycle:--> fast == slow!
Flag = True
while Flag:
if (not fast) or (not fast.next):
return None
fast = fast.next.next
slow = slow.next
if fast == slow:
Flag = False
fast = dummy.next
while fast!=slow:
fast = fast.next
slow = slow.next
return fast