LeetCode-Remove Nth Node From End of List

来源:互联网 发布:软件开发部门职责 编辑:程序博客网 时间:2024/06/03 13:01

/** * 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) {    ListNode *p = new ListNode(0);    p->next = head;    ListNode *f, *s;    f = s = p;    while(n--)    {        f = f->next;       }    while(f->next != NULL)    {        f = f->next;        s = s->next;    }    s->next = s->next->next;    return p->next;    }};

经过几个小时,渣渣终于把题解出来,虽然用的方法很土

主要问题出现在对链表操作不熟,没有搞清结构体指针的真正含义,导致出现bug。

这段代码严格上来说没有符合要,因为遍历了两次了,这篇博客提供的方法很好,需要多多加强http://blog.csdn.net/makuiyu/article/details/43315519

0 0