首页 > 其他 > 详细

Remove Nth Node From End of List

时间:2016-05-18 10:36:31      阅读:298      评论:0      收藏:0      [点我收藏+]

技术分享

/**
 * 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

原文:http://www.cnblogs.com/summerkiki/p/5504076.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!