刪除鏈表的倒數第N個節點


中英題面

  給定一個鏈表,刪除鏈表的倒數第 個節點並返回頭結點。

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

  例如,

  給定一個鏈表: 1->2->3->4->5, 並且 n = 2.

  當刪除了倒數第二個節點后鏈表變成了 1->2->3->5.

  For example,

     Given linked list: 1->2->3->4->5, and n = 2.

     After removing the second node from the end, the linked list becomes 1->2->3->5.

  說明:

  給的 n 始終是有效的。

  嘗試一次遍歷實現。

  Note:
  Given n will always be valid.
  Try to do this in one pass.

  
 
 
題目解讀
  主要難點在於一次遍歷完成。
 
算法
  使用系統棧完成,函數遞歸到鏈表尾時開始計數並返回,數 N 個節點后刪除。后來經過提醒,也可以使用兩個指針模擬一個長度為 N 的隊列,但筆者認為這嚴格意義上算兩次遍歷,所以還是選擇了前者,算法時間復雜度 O(N)。
 
代碼
 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     def removeNthFromEnd(self, head, n):
 9         """
10         :type head: ListNode
11         :type n: int
12         :rtype: ListNode
13         """
14         if (Solution.doit(self, head, n)):
15             return head.next
16         return head
17 
18     def doit(self, head, n):
19         x = y = 0
20         if (head.next):
21             x = Solution.doit(self, head.next, n)
22             if (x):
23                 y = x + 1
24         else:
25             y = 1
26         if (y == n + 1):
27             head.next = head.next.next
28             y = 0
29         return y

 

代碼解讀

  注意:以下內容完全根據筆者自己對 Python 3 的理解胡說八道。

  __init__():class 的構造函數(?)。
  self:類似 C++ 的 this。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM