- LeetCode 19. Remove Nth Node Fro
- 19. Remove Nth Node From End of
- 19. 删除倒数第N个结点
- LeetCode 19. Remove Nth Node Fro
- leetcode #19 Remove Nth Node Fro
- LeetCode-19 - Remove Nth Node Fr
- Remove Nth Node From End of List
- 19. Remove Nth Node From End of
- 19. Remove Nth Node From End of
- Remove Nth Node From End of List
解題思路 :
此類型題目 head 也有可能是被移除的候選人 最簡單的方法就是建立 dummy node 去連接 head 然後重設 head = dummy 接著就不用煩惱 head 遺失的問題了 其他問題可以用 2 pointer 方式解決
C++ code :
<pre><code>
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode *removeNthFromEnd(ListNode *head, int n) {
//create a dummy node in front of the head
ListNode *first = new ListNode(0);
first->next = head;
ListNode *second = first;
//head can be remove, so it's better to reset the head = the dummy node
head = first;
//for getting the length - n (distance)
for(int i = 0; i < n; i++)
{
first = first->next;
}
while(first->next)
{
first = first->next;
second = second->next;
}
first = second->next;
second->next = first->next;
delete first;
return head->next;
}
};
网友评论