Thursday, October 10, 2013

Remove Nth Node From End of List

Q:
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.
A:
-----------------two pointer 算法
public class RemoveNthNodeFromEndofList {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode header = new ListNode(2);
        header.next = head;
        // tow pointer technique
        ListNode slowRunner = header;
        ListNode fastRunner = header;
        // pooint fastRunner to Nth node
        for (int i = 0; i < n; i++) { // coz n is valid
            fastRunner = fastRunner.next;
        }
        while (fastRunner.next != null) {
            slowRunner = slowRunner.next;
            fastRunner = fastRunner.next;
        }
        if (n == 1) {
            slowRunner.next = null;
        } else {
            slowRunner.next = slowRunner.next.next;
        }
        return header.next;
    }
}



Mistakes:
1: fastRunner 在跑的时候,光顾忌了其next是否为空,  而没有考虑到, 当我们先设置fastRunner的时候(目的是保持slowRunner和fastRunner的距离为n),有可能已经跑出去了。 ------------solution,设置一个header。 
2: 返回header.next 而不是head, 是考虑到head有可能已经被删除掉了。  sigh~~~~~~~Tiger,  你太SB了

Learned:
-----------------------2nd pass------------------------

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode h = new ListNode(0);
        h.next = head;
        ListNode fast = h;
        ListNode slow = h;
        for(int i =0;i<n;i++){
            fast = fast.next;
        }
        while(fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return h.next;
    }
}





No comments:

Post a Comment