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) {
        if(head==NULL&&head->next==NULL)
            return NULL;
        ListNode* newhead=(ListNode*)malloc(sizeof(ListNode));
        newhead->next=head;
        ListNode* pre=newhead;
        ListNode* behind=newhead;
        n++;
        for(int i=0;i<n-1;i++)
            pre=pre->next;
        while(pre->next)
        {
            pre=pre->next;
            behind=behind->next;
        }
        behind->next=behind->next->next;
        return newhead->next;
    }
};

这道题要删除倒数第n个结点,因此要先找到倒数第n+1个结点,然后进行删除。由于可能删除的是链表的第一个结点,因此需要在链表开始插入一个空的头结点。

写题之前要提前想好几种特殊情况:

1. head指针为空,或者链表只有一个结点时,均返回NULL

2. 要删除的结点是头结点或者尾结点

posted on 2016-05-18 09:41  summerkiki  阅读(128)  评论(0编辑  收藏  举报