题目

Given a linked list, remove the nth node from the end of list and return its head.
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.

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

Python

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
class ListNode:
def __init__(self, x):
self.val = x;
self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
a, b = head, head
for i in range(n):
b = b.next
if b is None:
head = head.next
return head
while True:
a, b = a.next, b.next
if b is None:
head.next = head.next.next
return head
if b.next is None:
break
a.next = a.next.next
return head