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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!head || n <= 0) return head;
        ListNode dummynode(0), *h = &dummynode,*p = head,*e = p;
        h->next = head;
        int k = 0;
        for(;k < n && e; k++){
            e = e->next;
        }
        //n正好为总长度
        if (!e){
            return head->next;
        }
        while(p && e && e->next){
            p = p->next;
            e = e->next;
        }
        if (p) p->next = p->next->next;
        return h->next; 
    }
};

 

posted @ 2013-07-14 18:20  一只会思考的猪  阅读(135)  评论(0编辑  收藏  举报