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

19. Remove Nth Node From End of List

2017-10-16 15:55 330 查看
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个节点,通过两个指针,可以巧妙地在一次遍历中完成删除操作,具体思路如图:



在处理两个指针的时候要小心边界情况,图中加了一个Dummy节点,处理起来更方便。

/**
* 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 dummyNode = ListNode(0);
ListNode* dummy = &dummyNode;
//把DummyNode放在链表开头
dummy->next = head;

ListNode* first = dummy;
ListNode* second = dummy;
for (int i = 0; i < n + 1; i++) {
second = second->next;
}
while (second) {
first = first->next;
second = second->next;
}
first->next = first->next->next;
//这里注意要返回head,不是dummy
return dummy->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: