Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Note:Given n will always be valid.
Try to do this in one pass.
ListNode *removeNthFromEnd(ListNode *head, int n) {
//此题要求比遍历一遍搞定,需要一个指针来指向删除节点的前面节点,对于删除头结点的情况需要特殊考虑, p -> next和q-> next节点的关系需要搞清楚
ListNode *p = head, *q = head;
while (n--)
q = q -> next;
if (q == NULL)
return p -> next;
while (q -> next)
{
p = p -> next;
q = q -> next;
}
p -> next = p -> next -> next;
return head;
}
本文介绍了一种高效算法,用于从链表中删除倒数第N个节点,并返回链表的新头部。该算法仅需遍历一次链表,通过两个指针定位待删除节点,适用于各种链表操作场景。

443

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



