19. Remove Nth Node From End of List
就是设两个指针,他们所指的元素相隔n个元素,当一个指针指向末尾时,另一个就指向了目标元素。
/**
* 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) {
if(head->next == NULL || head == NULL)
return NULL;
ListNode* touch_end = head;
ListNode** target = &head;
while(n--){ touch_end = touch_end->next; }
if(touch_end == NULL)
return head->next;
while(touch_end && touch_end->next){
touch_end = touch_end->next;
target = &((*target)->next);
}
(*target)->next = (*target)->next->next;
return head;
}
};
本文介绍了一种高效算法,用于从单链表中移除倒数第N个节点。通过设置两个指针,初始时两指针间隔N个节点,随着链表遍历,当一指针到达末尾时,另一指针恰好位于目标节点前。这种方法仅需一次遍历即可完成节点移除。
643

被折叠的 条评论
为什么被折叠?



