1
+ """
2
+ Given a linked list, remove the n-th node from the end of list and return its head.
3
+
4
+ Example:
5
+
6
+ Given linked list: 1->2->3->4->5, and n = 2.
7
+
8
+ After removing the second node from the end, the linked list becomes 1->2->3->5.
9
+ Note:
10
+
11
+ Given n will always be valid.
12
+
13
+ Follow up:
14
+
15
+ Could you do this in one pass?
16
+
17
+ 给一个链表和一个n,删除从后数第n个节点。
18
+
19
+ n总是有效的。
20
+
21
+ 进阶条件是一次性完成。
22
+
23
+ 一开始的想法是总得先知道长度,然后才能倒数第n个吧。
24
+ 所以一开始用的列表,Python 中的列表非常适合做这个操作。
25
+ O(n) 遍历,然后剩下的索引操作就是 O(1) 了。
26
+
27
+ 失误的是,考虑到了如果删除的是head,但是写的话没写成 head.next,写成了 list_node[1],
28
+ 这样在链表中只有一个节点的时候就出错了...
29
+
30
+ 本题算是失败了。2 pass.
31
+
32
+ 效率上是 28ms。
33
+
34
+ 看了25ms的写法,感觉非常聪明。
35
+ 以前总是想,这样的必须得先过一遍知道长度才能做其他的事吧。
36
+ 这个的写法是,用一条像是绳子一样的。
37
+ |----------|
38
+ slow fast
39
+
40
+ 让fast走n步。
41
+ 然后fast和slow一起走,等fast.next是None,也就是到头了。那么slow就是要删除的点的前一个了。
42
+ 直接把slow.next与slow.next.next结合就达标了。
43
+ 如果走了n步后fast直接是None了。那么说明删除的节点是head,那么返回 head.next就好了。
44
+
45
+ 不过这个提交了两次也是 28ms..
46
+ 但是这个思路是真的棒。
47
+
48
+ 关键词:
49
+ 绳子。
50
+
51
+ 测试地址:
52
+ https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
53
+
54
+
55
+
56
+ """
57
+ # Definition for singly-linked list.
58
+ # class ListNode(object):
59
+ # def __init__(self, x):
60
+ # self.val = x
61
+ # self.next = None
62
+
63
+ class Solution (object ):
64
+ def removeNthFromEnd (self , head , n ):
65
+ """
66
+ :type head: ListNode
67
+ :type n: int
68
+ :rtype: ListNode
69
+ """
70
+ my_head = my_trail = head
71
+ for i in range (n ):
72
+ my_head = my_head .next
73
+
74
+ if not my_head :
75
+ return head .next
76
+
77
+ while my_head .next :
78
+ my_head = my_head .next
79
+ my_trail = my_trail .next
80
+
81
+ my_trail .next = my_trail .next .next
82
+
83
+ return head
84
+ # list_node = []
85
+ # my_head = head
86
+ # while my_head:
87
+ # list_node.append(my_head)
88
+ # my_head = my_head.next
89
+
90
+ # if n == len(list_node):
91
+ # try:
92
+ # return list_node[1]
93
+ # except:
94
+ # return None
95
+
96
+ # if n == 1:
97
+ # list_node[-2].next = None
98
+ # return list_node[0]
99
+
100
+ # list_node[-(n+1)].next = list_node[-(n-1)]
101
+
102
+ # return list_node[0]
0 commit comments