Search This Blog

Monday, December 10, 2012

LeetCode:Remove Nth Node From End of List

Remove Nth Node From End of List
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.

class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        ListNode *temp = head;
        while (n > 0 && temp != NULL) {
            temp = temp->next;
            --n;
        }
        if (n == 0) {
            if (temp == NULL) {
                head = head->next;
                return head;
            } else {
                ListNode *curr = head;
                while (temp->next != NULL) {
                    temp = temp->next;
                    curr = curr->next;
                }
                curr->next = curr->next->next;
            }
        }
        return head;
    }
};


public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(n<=0) return head;
        ListNode prev = new ListNode(0);
        prev.next = head;
        head = prev;
        
        ListNode n1=head.next,n2=head.next;
        
        int k=n;
        while(n2!=null && k>0){
            n2=n2.next;
            k--;
        }
        if(k>0) return n1;
        
        while(n2!=null){
            n2=n2.next;
            n1=n1.next;
            prev=prev.next;
        }
        prev.next=n1.next;
        
        return head.next;
    }
}

No comments: