<LeetCode OJ> 19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

Total Accepted: 85357  Total Submissions: 305369  Difficulty: Easy

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.


可行的方案,但是不符合要求:DONE

首先统计有多少个节点m,再计算顺序遍历m-n个节点即可找到要删除的节点。

/**
 * 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)  
            return NULL;
        ListNode* pCur=head;
        //统计链表长度
        int m=0;
        while(pCur !=NULL)
        {
            m++;
            pCur=pCur->next;
        }
        
        int kill=m-n;//要删除的顺序位置
        
        pCur=head;
        if(kill==0){//如果是头结点
            head=head->next;
            delete pCur;
            pCur=NULL;
            return head;
        }
       else{
            ListNode* pPre=NULL;
            int cnt=0;//找到要删除的位置
            while(pCur && cnt<kill){
                pPre=pCur;
                pCur=pCur->next;
                cnt++;
            }
            //执行删除
            pPre->next=pCur->next;
            delete pCur;
            pCur=NULL;
            
            return head;
       }
    }
};



比较优秀的解法:DONE

像游标卡尺一样,我们就保持两个指针相距为n,首先我们保持一个指针先移动n个节点, 然后同时移动两个指针,使得两指针始终相距了n个位置,当先移动的指针移动到了末尾时也就确定了该删除节点了。注意边界条件。

/**
 * 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) {
        //n总是安全的,不用特殊案例判断
        ListNode* tmphead=new ListNode(0);//为了能够删除第一个节点,我们申请在头结点之前还有一个节点
        tmphead->next=head;
        ListNode* fast=tmphead;
        ListNode* slow=tmphead;
        //
        for(int i=0;i<n;i++)
            fast=fast->next;
        while(fast->next!=NULL)
        {
            fast=fast->next;
            slow=slow->next;
        }
        slow->next=slow->next->next;
        return tmphead->next;
    }
};






注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50370224

原作者博客:http://blog.csdn.net/ebowtang

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值