1. 程式人生 > 其它 >Leetcode(Python3) 19. Remove Nth Node From End of List

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

技術標籤:leetcode連結串列資料結構leetcode單鏈表

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

# one pass with new head node
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(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#one pass without new head node
class Solution(object):
    def removeNthFromEnd(self, head, n):
        p, q = head, head
        while n:
            q = q.next
            n -=1
        # delete the first node
        if q == None:
            return p.next
        while q.next:
            p = p.next
            q = q.next
        p.next = p.next.next
        return head
# 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