Description:
Given a linked list, remove the n-th node from the end of list and return its head.
Example1:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
提交代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
if (head == NULL||head->next==NULL)
return NULL;
int i;
int len=0,pos;
struct ListNode* p = head;
//calculate the len of the list
while (p != NULL)
{
len++;
p = p->next;
}
pos = len - n;
p = head;
if (pos == 0)
return p->next;
for (i = 0; i < pos-1; i++)
p = p->next;
struct ListNode* tmp = p->next;
p->next = p->next->next;
free(tmp);
return head;
}
运行结果:

其他:
提交历史中有这个报错:

报错的代码行在这里:

报错的原因是刚开始我忘记加[p=head;]这句代码了,所以p的指向是混乱的,
所以我后面return p->next的时候,编译器就不知道我的p到底指向哪里。
本文介绍了一种算法,用于从链表中删除倒数第N个节点,并提供了详细的实现代码。通过计算链表长度并定位到待删除节点的前一个位置,实现了节点的高效移除。
634

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



