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

[leetcode] 19. Remove Nth Node From End of List

2016-04-18 20:34 453 查看
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个节点,题目难度为Easy。

题目的关键是如何找倒数第N个节点,有经验的同学可能很容易想到用双指针法,让fast指针先走N个节点,然后同时移动快慢指针,当fast指针到达链表尾部时slow指针指向的节点即是倒数第N个节点。另外需要注意的是,如果倒数第N个节点是头节点需要特殊处理,具体代码:class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fast = head;
ListNode* slow = head;
ListNode* prev = NULL;
int cnt = 0;

while(fast && cnt<n) {
fast = fast->next;
cnt++;
}
while(fast) {
fast = fast->next;
prev = slow;
slow = slow->next;
}

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