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

Leetcode 19. Remove Nth Node From End of List

2018-01-30 09:58 337 查看
原题:

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.

解决方法:
用前后指针的方法来解这道题,通用第二个指针是指向指针的指针,这样可以直接修改直接的值。

第一个指针先往前走n-1步,然后两个指针一起往前走,直到第一个指针的下一个指针为空,那第二个指针的位置就是当前需要删除的指针。将其指向下一个指针,相当于将该指针删除。

代码:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* l1 = head, **l2 = &head;
for(int i = 1; i < n; i++)
l1 = l1->next;
while(l1->next != NULL){
l1 = l1->next;
l2 = &( (*l2)->next);
}

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