[Leetcode] 19 - Remove Nth Node From End of List
2015-01-20 17:25
381 查看
原题链接:https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
这道题是移除倒数第n个node,做法是保持2个指针,一快一慢,快指针先走n步,然后快慢指针同时走,直到快指针变成null。这时将慢指针的值改为next的值。(注意,慢指针其实是指针的指针,以为为了改变指向当前node的指针的值)。个人感觉这题其实要非常仔细做才行,不然很容易写错。属于想法简单,但是需要仔细和强大的内心。
/**
* 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* fast = head;
ListNode** slowpp = NULL;
int i = 0;
while (fast) {
fast = fast->next;
++i;
if (i == n) {
slowpp = &head;
} else if (i > n) {
slowpp = &((*slowpp)->next);
}
}
if (*slowpp) {
ListNode* next = (*slowpp)->next;
ListNode* cur = (*slowpp);
delete(cur);
*slowpp = next;
}
return head;
}
};
这道题是移除倒数第n个node,做法是保持2个指针,一快一慢,快指针先走n步,然后快慢指针同时走,直到快指针变成null。这时将慢指针的值改为next的值。(注意,慢指针其实是指针的指针,以为为了改变指向当前node的指针的值)。个人感觉这题其实要非常仔细做才行,不然很容易写错。属于想法简单,但是需要仔细和强大的内心。
/**
* 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* fast = head;
ListNode** slowpp = NULL;
int i = 0;
while (fast) {
fast = fast->next;
++i;
if (i == n) {
slowpp = &head;
} else if (i > n) {
slowpp = &((*slowpp)->next);
}
}
if (*slowpp) {
ListNode* next = (*slowpp)->next;
ListNode* cur = (*slowpp);
delete(cur);
*slowpp = next;
}
return head;
}
};
相关文章推荐
- [leetcode 19] Remove Nth Node From End of List
- [LeetCode]19 Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- [Leetcode 19, Easy] Remove Nth Node From End of List
- [Leetcode] 19. Remove Nth Node From End of List
- leetcode19-Remove Nth Node From End of List
- [Leetcode 19, Easy] Remove Nth Node From End of List
- LeetCode41/19 First Missing Positive/Remove Nth Node From End of List ****
- leetcode[19]Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- 【LeetCode】19. Remove Nth Node From End of List (2 solutions)
- [Leetcode 19] 19 Remove Nth Node From End Of List
- 19. Remove Nth Node From End of List Leetcode Python
- leetcode 19 Remove Nth Node From End of List
- Leetcode_19_Remove Nth Node From End of List
- LeetCode(19) Remove Nth Node From End of List
- LeetCode | #19 Remove Nth Node From End of List
- leetcode_19_Remove Nth Node From End of List
- LeetCode19——Remove Nth Node From End of List
- leetcode-19 Remove Nth Node From End of List