LintCode 174:Remove Nth Node From End of List

来源:互联网 发布:网络打印机安装失败 编辑:程序博客网 时间:2024/06/08 09:09
Description:

Given a linked list, remove the nth node from the end of list and return its head.


Note:

需要注意的边界情况:

当需要删除的结点是head结点时,head会发生改变。

当n超过结点个数时,表明没有需要删除的结点。


Code:

/** * Definition of ListNode * class ListNode { * public: *     int val; *     ListNode *next; *     ListNode(int val) { *         this->val = val; *         this->next = NULL; *     } * } */class Solution {public:    /**     * @param head: The first node of linked list.     * @param n: An integer.     * @return: The head of linked list.     */    ListNode *removeNthFromEnd(ListNode *head, int n) {        // write your code here        int i;        ListNode* first = head;        ListNode* second = head;        bool flag = false;        for(i=0;i<n-1;i++){            if(first)                first=first->next;            else                break;        }        if(i<n-1||!first)            return head;        while(first->next&&first->next->next){            first=first->next;            second=second->next;            flag = true;        }        ListNode * deleted;        if(!flag){            deleted = head;            head=head->next;        }        else{            deleted = second->next;            second->next = deleted->next;        }        delete deleted;        return head;    }};


原创粉丝点击