Remove Nth Node From End of List

Posted summerkiki

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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. 要删除的结点是头结点或者尾结点

以上是关于Remove Nth Node From End of List的主要内容,如果未能解决你的问题,请参考以下文章

Remove Nth Node From End of List

19. Remove Nth Node From End of List

Remove Nth Node From End of List

Remove Nth Node From End of List

LC_19. Remove Nth Node From End of List

leetcode:Remove Nth Node From End of List