Given a linked list, remove the nth node from the end of list and return its head. Given n will always be valid and try to do this in one pass.

For example,

1
2
3
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.

思路

这是一道非常典型的快慢指针题。双指针的操作在链表中比较常用,这样的操作可以省去频繁对链表进行遍历的开销,非常方便。

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
# 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
"""
fast = head
headflag = 1
# 利用快指针来定位倒数第n个元素
for i in range(n):
fast = fast.next
# 慢指针必须要指到目标元素前一个元素
# 才能执行单链表的删除操作
if (fast):
fast = fast.next
headflag = 0
slow = head
while(fast):
fast = fast.next
slow = slow.next
# 经过循环,现在慢指针已经指向目标元素的前一个元素了
if (slow == head):
# 边界条件:如果慢指针还在头部
if (headflag):
# 删除第一个元素
head = slow.next
else:
slow.next = slow.next.next
else:
slow.next = slow.next.next
return head