1. 程式人生 > >leetcode:19 刪除連結串列的倒數第N個節點(python)

leetcode:19 刪除連結串列的倒數第N個節點(python)

給定一個連結串列,刪除連結串列的倒數第 個節點,並且返回連結串列的頭結點。

示例:

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

當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.

說明:

給定的 n 保證是有效的。

進階:

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

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

class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
#         temp = head
#         count = 0
#         while temp!= None:
#             temp = temp.next #掃描操作,temp為掃描指標
#             count += 1
            
#         temp = head #重新賦值
#         index = 0
#         if count== n:
#             return head.next #只有兩個元素,刪除第一個即可
#         else:
#             while index!=(count-n-1): #
#                 temp = temp.next
#                 index += 1
#             temp.next = temp.next.next # 一般情況下的元素刪除
#             return head
    
    
    
        length = 0
        p = head
        
        while p:  #遍歷操作
            length += 1
            p = p.next 
        
        idx = length - n #要刪除的位置
        #pre.next = pre.next.next 可以刪除指定位置
        
        p = head #重新賦值
        
        if idx == 0:
            return p.next
        
        for i in range(length):
            if i == idx - 1: #刪除位置的前一個位置,
                p.next = p.next.next #刪除指定位置
                return head
            else:
                p = p.next #繼續遍歷