lintcode-删除链表中倒数第n个节点-174

来源:互联网 发布:最大子数组 动态规划 编辑:程序博客网 时间:2024/06/06 03:22

给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。


样例

给出链表1->2->3->4->5->null和 n = 2.

删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.


注意

链表中的节点个数大于等于n

挑战

O(n)时间复杂度

/** * Definition of ListNode * class ListNode { * public: *     int val; *     ListNode *next; *     ListNode(int val) { *         this->val = val; *         this->next = NULL; *     } * } */class Solution {public:       ListNode *removeNthFromEnd(ListNode *head, int n) {        if(!head)            return NULL;        ListNode *slow=head;        ListNode *fast=slow;        ListNode *cur;        while(fast&&n){            fast=fast->next;            --n;        }        if(!fast){            if(n>0)                return head;            ListNode *tmp=head;            head=head->next;            if(tmp){                tmp->next=NULL;                free(tmp);            }            return head;        }        while(fast){            cur=slow;            slow=slow->next;            fast=fast->next;        }        cur->next=slow->next;        slow->next=NULL;        free(slow);        return head;    }};



0 0
原创粉丝点击