leetcode--19. Remove Nth Node From End of List

来源:互联网 发布:手机模拟笛子软件 编辑:程序博客网 时间:2024/06/18 03:59

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.

2 pointer的方法。先让一个ptr走n步,使得两个pointer构造出一个gap之后,再共同前进。

构造一个伪头结点,方便处理删除头结点的case。

/** * 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 *pseudo = new ListNode(0);        pseudo->next = head;        ListNode *p1 = pseudo;        ListNode *p2 = pseudo;        while(n) {            p1 = p1->next;            n--;        }        while(p1->next){            p1 = p1->next;            p2 = p2->next;        }        ListNode *tmp = p2->next;        p2->next = p2->next->next;        delete tmp;        head = pseudo->next;        delete pseudo;        return head;    }};


原创粉丝点击