移除链表倒数第n个节点。

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.

另外,题目要求遍历一遍完成。

我的思路是这样的:

扫描一遍链表s,构建一个长度为n+1的列表l,列表中的元素依次是原链表中的len(s) - n个元素到最后一个元素。

例如:s:1->2->3->4->5, n=2

那么:l:[3,4,5]

再将列表中的l[0]指向l[2]

 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 head.next is None:
15             return None
16         tmp = [head, ]
17         nxt = head.next
18         while nxt is not None:
19             tmp.append(nxt)
20             if len(tmp) > n + 1:
21                 tmp.remove(tmp[0])
22             nxt = nxt.next
23         if len(tmp) < n + 1:
24             return head.next
25         if n == 1:
26             tmp[0].next = None
27         else:
28             tmp[0].next = tmp[2]
29         return head