Given a linked list, remove the nth node from the end of list and return its head.
For example,
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.
Try to do this in one pass.
很简单的一个用链表的实现,但是细节总是难以全部想到,想要一次完成没有错误的编程还需要联系。
一开始,不知道怎么用one pass完成,就写了个脑残的。
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode* first = (struct ListNode*)malloc(sizeof(struct ListNode));//leecode中的链表没有不包含数据的头指针!自己模拟一个
first->next = head;
struct ListNode* temp = first;
int i, N;
for (i = 0; temp->next != NULL; i++)
{
temp = temp->next;
}
N = i - n + 1;
if (N == 1 && n == 1)//如果链表长度为1,返回NULL
{
return NULL;
}
else{
temp = first;
for (i = 1; i < N; i++)
{
temp = temp->next;
}
temp->next = temp->next->next;
}
return first->next;//因为可能删除第一个节点
}
百度了一下,找到one pass的方法,使用双指针。以前听过怎么快速定位到中间位置,设两个指针,一个跑一步,一个跑两步,但是没能够举一反三。
struct ListNode* first = (struct ListNode*)malloc(sizeof(struct ListNode));
first->next = head;
struct ListNode* temp1 = first;
struct ListNode* temp2 = first;
int i, N;
for (i = 0; i<n; i++)
{
temp2 = temp2->next;
}
while (temp2->next != NULL)
{
temp1 = temp1->next;
temp2 = temp2->next;
}
temp1->next = temp1->next->next;
return first->next;