您的位置:首页 > Web前端 > Node.js

LeetCode 19. Remove Nth Node From End of List

2016-09-09 21:26 302 查看

描述

给出一条链表,删除从右往左数的第n个节点

解决

因为不知道ListNode是如何构成的,所以不考虑删除内存,只是修改了指针。先遍历一遍统计节点个数,然后再利用辅助指针来移动扫描节点的位置。

/**
* 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) {
char buf[sizeof(ListNode)];
ListNode* ptrHead = new(buf) ListNode(-1);
ptrHead -> next = head;
int cnt = 0;
while (head){
++cnt;
head = head -> next;
}
int pos = cnt - n + 1, cur = 1;
if (n == 0 || n > cnt)
return NULL;
ListNode* now = ptrHead -> next;
ListNode* pre = ptrHead;
ListNode* post = ptrHead -> next ? ptrHead -> next -> next : NULL;
// cout << pos << ' ' << cur << endl;
while (now){
if (cur == pos){
pre -> next = post;
//      cout << pos << ' ' << cur << endl;
if (pos == 1){
ptrHead -> next = post;
}
break;
}
ListNode* tmp = now;
now = now -> next;
post = now ? now -> next: NULL;
pre = tmp;
++cur;
}
return ptrHead -> next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode