2024/11/27 【連結串列】LeetCode 24 兩兩交換連結串列中的節點 & LeetCode 19 刪除連結串列的倒數第N個節點

axuu發表於2024-11-27

24. 兩兩交換連結串列中的節點 - 力扣(LeetCode)

程式碼隨想錄

遞迴方式:沒有想到

# 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]:
        if head is None or head.next is None:
            return head
        
        pre = head
        cur = head.next
        next = head.next.next

        cur.next = pre
        pre.next = self.swapPairs(next)

        return cur   

19. 刪除連結串列的倒數第 N 個結點 - 力扣(LeetCode)

程式碼隨想錄給出的一次遍歷的雙指標法,沒有想到

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy_head = ListNode(next=head)
        slow = fast = dummy_head
        
        for i in range(n+1):
            fast = fast.next
        
        while fast:
            slow = slow.next
            fast = fast.next

        slow.next = slow.next.next

        return dummy_head.next

相關文章