Remove n’th node from end of list#
Levels: level-3
Data structures: linkedlist
Practice Link#
Description#
- Given a linked list, remove the n-th node from the end of list and return its head.
Note:
- Given n will always be valid.
Example#
1Given linked list: 1->2->3->4->5, and n = 2.
2After removing the second node from the end, the linked list becomes 1->2->3->5.Follow up:
- Could you do this in one pass?
Python Solution#
1class ListNode(object):
2 def __init__(self, x):
3 self.val = x
4 self.next = None
5
6
7class Solution:
8 def removeNthFromEnd(self, head, n):
9 if not head:
10 return
11 fast = slow = head
12 for _ in range(n):
13 if not fast.next:
14 raise Exception("less than n nodes found")
15 fast = fast.next
16 if not fast:
17 return head.next
18 while fast.next:
19 fast = fast.next
20 slow = slow.next
21 slow.next = slow.next.next
22 return head