24. 兩兩交換連結串列中的節點
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def swapPairs(self, head):
if head is None:
return
dummy_head = ListNode()
dummy_head.next = head
curr = head
prev = dummy_head
after = curr.next
while curr is not None and after is not None:
prev.next = curr.next
curr.next = after.next
after.next = curr
prev = curr
curr = curr.next
if curr is not None:
after = curr.next
return dummy_head.next
19.刪除連結串列的倒數第N個節點
快慢指標太神啦
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
dummy_head = ListNode()
dummy_head.next = head
slow_ptr = dummy_head
fast_ptr = dummy_head
diff = n + 1
if n == 0:
return
while diff != 0 and fast_ptr:
fast_ptr = fast_ptr.next
diff -= 1
while fast_ptr:
slow_ptr = slow_ptr.next
fast_ptr = fast_ptr.next
slow_ptr.next = slow_ptr.next.next
return dummy_head.next
面試題 02.07. 連結串列相交
142.環形連結串列II