19. 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.
思路:定义俩个变量,一个先走n步,然后俩个同时走,后者到达末尾时,前者删除掉next即可
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
   struct ListNode *first=head;
struct    ListNode *end=head;
    while(n--){
        end=end->next;
    }
    if(end==NULL){
        return head->next;
    }
    while(end->next!=NULL){
        first=first->next;
        end=end->next;
    }
    first->next=first->next->next;
    return head;
}


posted on 2016-07-07 22:50  胖胖的乓乓  阅读(120)  评论(0编辑  收藏  举报

导航