Leetcode(Python3) 19. Remove Nth Node From End of List

yuqiong11發表於2020-12-10

The question is :Given the head of a linked list, remove the nth node from the end of the list and return its head.

A follow-up question: Could you do this in one pass?

Example input and output:
在這裡插入圖片描述
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

題目要求刪除連結串列倒數第n個結點,並返回刪除後的連結串列。這個練習可以幫助理解連結串列的指標到底是怎麼工作的。

先放三段通過測試的程式碼,第二段是我照著第一段寫的,第一段和第三段是其他人的解法。之後會再補充一點註釋。

# 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: ListNode, n: int) -> ListNode:
        v_head = ListNode()  #建立空結點
        v_head.next = head  #指向第一個結點
        p = q = v_head  #p,q兩個頭結點
        for _ in range(n):
            q = q.next
        while q.next:
            p = p.next
            q = q.next
        p.next = p.next.next
        return v_head.next
# 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: ListNode, n: int) -> ListNode:
        v_head = ListNode()
        v_head.next = head
        sz = 0
        p = q = v_head
        while p.next:
            p = p.next
            sz += 1
        i = 0
        while i <= sz - n - 1:
            q = q.next
            i += 1
        q.next = q.next.next
        return v_head.next
class Solution(object):
    def removeNthFromEnd(self, head, n):
        # traverse for the first time and get the location(k) of the node we want to delete
        countNode = head  #let countNode point to the same node as head
        numNodes = 0 
        while countNode is not None:
            countNode = countNode.next
            numNodes += 1
        k = numNodes - n
        #create two pointers prev and ptr, prev is always 1-lag behind ptr, after traversing again, ptr point to the node we want to delete, prev to the previous node
        prev = None
        ptr = head
        while k != 0:
            prev = ptr
            ptr = ptr.next
            k -= 1
        # A solution without a new head node, so inserting the first node and the other nodes is different
        if prev is None:
            return head.next
        else:
            prev.next = ptr.next
            ptr.next = None
            return head

相關文章