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

[LeetCode]Remove Nth Node From End of List

2015-07-11 22:18 615 查看


就是找到要删除的节点的前一个节点
/**
* 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) {
int sum =0;
ListNode* p = head;
while(p!=NULL){
++sum;
p=p->next;
}
if(n==0)
return head;
if(n==sum)
return head->next;
ListNode* q;
q->next= head;
int j= 0;   //指向要去的前一个节点
while(j!=sum-n){
q = q->next;
++j;
}
q->next = q->next->next;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: