0
点赞
收藏
分享

微信扫一扫

8道链表常考题-一次遍历删除链表倒数第N个节点


​​https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/​​

可以使用两个指针而不是一个指针。第一个指针从列表的开头向前移动 n+1 步,而第二个指针将从列表的开头出发。现在,这两个指针被 nn 个结点分开。我们通过同时移动两个指针向前来保持这个恒定的间隔,直到第一个指针到达最后一个结点。此时第二个指针将指向从最后一个结点数起的第 n 个结点。我们重新链接第二个指针所引用的结点的 next 指针指向该结点的下下个结点。

8道链表常考题-一次遍历删除链表倒数第N个节点_结点

public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// Advances first pointer so that the gap between first and second is n nodes apart
for (int i = 1; i <= n + 1; i++) {
first = first.next;
}
// Move first to the end, maintaining the gap
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}

ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *ptr = head;
ListNode *pre = NULL; //两个指针相隔n
int tem = 0;
while(ptr)
{
if(tem >= n) pre = (pre == NULL) ? head : pre->next;
ptr = ptr->next;
tem ++;
}
if(pre != NULL){
pre->next = pre->next->next;
}else{
return head->next;
}

return head;
}


举报

相关推荐

0 条评论