19. Remove Nth Node From End of List

来源:互联网 发布:ubuntu查看ip 编辑:程序博客网 时间:2024/06/06 23:17

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;}


0 0