Last active
July 18, 2022 11:03
-
-
Save icameling/0246af4ff4f6ff059885684f7487d1c4 to your computer and use it in GitHub Desktop.
#链表 #删除链表的倒数第N个节点
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* ListNode *next; | |
* ListNode() : val(0), next(nullptr) {} | |
* ListNode(int x) : val(x), next(nullptr) {} | |
* ListNode(int x, ListNode *next) : val(x), next(next) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
ListNode* removeNthFromEnd(ListNode* head, int n) { | |
ListNode* dummy = new ListNode(0); | |
dummy->next = head; | |
// [head, cur node] 区间有 n 个node | |
ListNode* cur = dummy; | |
for (int i = 0; i < n; ++i) { | |
cur = cur->next; | |
} | |
// [candidate, cur] 区间有 n+1 个node | |
ListNode* candidate = dummy; | |
while (cur->next != NULL) { | |
cur = cur->next; | |
candidate = candidate->next; | |
} | |
candidate->next = candidate->next->next; | |
// delete candidate->next; | |
return dummy->next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment