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

LeetCode:Remove Nth Node From End of List

2015-07-16 15:55 627 查看
problem:

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.

Note:

Given n will always be valid.

Try to do this in one pass.

Solution:解决方式采用双指针,前后指针相差n

/**
* 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) {
//题意是要删除从最后一个节点往前数的第n个节点 考虑到只有一个节点时没有办法删除 加一个dummy

ListNode *dummy=new ListNode(-1);
dummy->next=head;
ListNode *pre=dummy;
ListNode *last=dummy;

//找到last的初始位置
while(n--)
{
last=last->next;
}

while(last->next!=NULL)
{
pre=pre->next;
last=last->next;
}
//删除节点
ListNode *object=pre->next;
pre->next=pre->next->next;
delete object;

return dummy->next;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: