-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquestion_2.py
More file actions
59 lines (48 loc) · 1.26 KB
/
question_2.py
File metadata and controls
59 lines (48 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python
# @Time : 2018/5/5 下午1:53
# @Author : cancan
# @File : question_2.py
# @Function : 删除链表的倒数第N个节点
"""
Question:
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
Example:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
Note:
给定的 n 保证是有效的。
Follow up:
你能尝试使用一趟扫描实现吗?
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if not head.next:
return None
nodes = [head]
t = head.next
while t:
nodes.append(t)
t = t.next
if n == 1:
nodes[-2].next = None
else:
nodes[-n].val = nodes[-n].next.val
nodes[-n].next = nodes[-n].next.next
return head
if __name__ == "__main__":
a = Solution()
l1 = ListNode(1)
l2 = ListNode(2)
l1.next = l2
a.removeNthFromEnd(l1, 1)
print(l1.next)