04天【程式碼隨想錄演算法訓練營34期】 第二章 連結串列part02 (● 24. 兩兩交換連結串列中的節點 ● 19.刪除連結串列的倒數第N個節點 ● 面試題 02.07. 連結串列相交 ● 142.環形連結串列II )

MiraMira發表於2024-03-24

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

相關文章