码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Nth Node From End of List

时间:2016-05-18 10:37:00      阅读:187      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!