天天看點

打卡群刷題總結0625——删除連結清單的倒數第N個節點

題目:19. 删除連結清單的倒數第N個節點

連結:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list

給定一個連結清單,删除連結清單的倒數第 n 個節點,并且傳回連結清單的頭結點。

示例:

給定一個連結清單: 1->2->3->4->5, 和 n = 2.

當删除了倒數第二個節點後,連結清單變為 1->2->3->5.

說明:

給定的 n 保證是有效的。

進階:

你能嘗試使用一趟掃描實作嗎?

解題:

1、删除節點,得分兩種情況進行處理:頭結點和普通節點。

代碼:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        fast = head
        while n > 0:
            fast = fast.next
            n -= 1

        # 頭結點
        node = ListNode(0)
        node.next = head
        head = node

        slow = head
        while fast:
            fast = fast.next
            slow = slow.next

        node = slow.next
        slow.next = slow.next.next
        del node
        return head.next           

複制