LeetCode #133 Remove Nth Node From End of List

LeetCode #133 Remove Nth Node From End of List


My Code:

#include <iostream>
#include <cstdlib>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode *curr = head;
        int length = 0;
        while(curr){
            curr = curr->next;
            length ++;
        }
        //cout<<length<<endl;
        if(length == n)
            return head->next;
        int i = 0;
        curr = head;
        while ((length - i )!= (n + 1) ){
            curr = curr->next;
            i++;
        }
        curr->next = curr->next->next;
        return witHead->next;
    }
};

int main()
{
    int i = 1;
    struct ListNode *head = (ListNode *)malloc(sizeof(ListNode));
    head->val = i;
    struct ListNode *curr = head;
    while (i < 1){
        i++;
        curr->next = (ListNode *)malloc(sizeof(ListNode));
        curr->next->val = i;
        curr = curr->next;
    }
    curr->next=NULL;
    curr = head;
    while(curr){
        cout<<curr->val<<" ";
        curr = curr->next;
    }
    cout<<endl;
    Solution solution;
    head = solution.removeNthFromEnd(head, 1);
    curr = head;
    while(curr){
        cout<<curr->val<<" ";
        curr = curr->next;
    }
    return 0;
}

看过讨论之后,自己又写了,但是没按照答案在链表前加一个头的方法来,结果发现需要考虑的多种特殊情况解决不了,改回机智的方法:

class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {

        if(head == NULL)
            return NULL;
        ListNode *witHead = (ListNode *)malloc(sizeof(ListNode));
        witHead->val = -1;
        witHead->next = head;
        ListNode *former = witHead, *latter = witHead;
        while(n&&latter->next){//find the node at end of list
            latter = latter->next;
            n--;
        }

        while(latter->next){
            latter = latter->next;
            former = former->next;
        }
        ListNode *target = former->next;
        former->next = target->next;
        free(target);
        return witHead->next;
    }
};

转载于:https://www.cnblogs.com/Haeckel/p/3897765.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值