删除链表中倒数第n个元素

要求

删除链表中倒数第n个元素,例如1->2->3->4->5->6,n=2,返回1->2->3->4->6

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
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) {
        if (head==NULL) {
            return head;
        }else{
            ListNode* newHead = new ListNode(0);
            newHead->next = head;
            ListNode* pre = newHead;
            ListNode* p = newHead;
            for (int i=0; i<n; i++) {
                p = p->next;
            }
            while (p->next!=NULL) {
                pre = pre->next;
                p = p->next;
            }
            pre->next = pre->next->next;
            return newHead->next;
        }
    }
};
int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    return 0;
}

Comments