04天【代码随想录算法训练营34期】 第二章 链表part02 (● 24. 两两交换链表中的节点 ● 19.删除链表的倒数第N个节点 ● 面试题 02.07. 链表相交 ● 142.环形链表II )
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. 链表相交
有点奥数的感觉,稍后再学一下哈希和快慢指针吧
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
A, B = headA, headB
while A != B:
A = A.next if A else headB
B = B.next if B else headA
return A
142.环形链表II
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast_ptr = head
slow_ptr = head
while fast_ptr and fast_ptr.next:
fast_ptr = fast_ptr.next.next
slow_ptr = slow_ptr.next
if fast_ptr == slow_ptr:
slow_ptr = head
while slow_ptr != fast_ptr:
fast_ptr = fast_ptr.next
slow_ptr = slow_ptr.next
return slow_ptr
return None