[Leetcode 19] 19 Remove Nth Node From End Of List

Problem:

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.

 

Analysis:

Use an auxilary pointer that n procedeed the current node. When the aux pointer is null, then the current pointer is the pointer to be removed;

Also need a pointer that 1 succeed the current point for update.

This is a one pass algorithm, so the time complecity is O(n); and space complexity is O(1);

 

Code:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode removeNthFromEnd(ListNode head, int n) {
14         // Start typing your Java solution below
15         // DO NOT write main() function
16         ListNode toRmv = head, aux = head, preRmv = head;
17         
18         for (int i=0; i<n; ++i)
19             aux = aux.next;
20         
21         while (aux != null) {
22             preRmv = toRmv;
23             toRmv = toRmv.next;
24             aux = aux.next;
25         }
26         
27         if (toRmv == head) {
28             head = head.next;
29         } else {
30              preRmv.next = toRmv.next;
31         }
32         
33         return head;
34     }
35 }
View Code

 

 

Attention:

If the Node to be removed is the head, need process it separately.

posted on 2013-05-19 03:37  freeneng  阅读(172)  评论(0编辑  收藏  举报

导航