现在的位置: 首页 > 综合 > 正文

Leetcode: Remove Nth Node From End of List

2013年12月12日 ⁄ 综合 ⁄ 共 629字 ⁄ 字号 评论关闭

http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode *current=head, *advance=head;
        for(int i=0;i<n;i++) advance=advance->next;
        // It is very important to take care of the case where the head node should be deleted
        if(advance==NULL){
            ListNode* NextOne = head->next;
            delete head;
            return NextOne;
        }
        while(advance->next!=NULL){
            current=current->next;
            advance=advance->next;
        }
        ListNode* NextOne = current->next->next;
        delete current->next;
        current->next=NextOne;
        return head;
    }
};

抱歉!评论已关闭.