leetcode|19. Remove Nth Node From End of List

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

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.


最开始的时候审错题目了,注意是从尾部开始的第几个。

在debug的时候很搞笑的是使用printf(length);丝毫没觉得有任何问题,真是写python写习惯了哈哈哈,有的句子都不加分号了。

自己写的最暴力的算法。
提交报错:   member access within null pointer of struct"ListNode"

应该还是指针的问题吧,估计。http://blog.sina.com.cn/s/blog_12af6f37f0102wrs7.html 
不知道该怎么改,放弃了。
/**
 * 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个
        int length=0;
        ListNode* pre=head;
        while(pre!=NULL){
            pre=pre->next;
            length++;
        }
        printf("%d\n",length);
        if(length<=1){
            return head->next;
        }
        pre=head;
        for(int i=1;i<length-n+1;i++){
            pre=pre->next;
        }
        pre->next=pre->next->next;
        return head;
    }
};


以下,继续学习优秀算法。

对于之前的算法进行优化,需要找的是倒数第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* pre=new ListNode(0);
        pre->next=head;
        ListNode* sec=pre;
        ListNode* fir=pre;
        for(int i=0;i<n;i++){
            sec=sec->next;
        }
        while(sec->next!=NULL){
            sec=sec->next;
            fir=fir->next;
        }
        fir->next=fir->next->next;
        return pre->next;
    }
};

就像找一个列表的中间位置的值一样。
这个其实这是对之前的方法做了优化,但使却没有出现null pointer的问题,大概是上面的代码错了吧 唉。

猜你喜欢

转载自blog.csdn.net/xueying_2017/article/details/80456898