題目
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.
分析
給定一個鏈表,移除從隊尾向前數的第n個節點。
由于是鏈表,只能從前向后尋找數據,所以先遍歷看一共多少數據,即可知道要移除的倒數第幾個數字是正數的第幾個數字。
之后尋找該幾點和其前節點,然后替換next指針即可,C代碼如下,已通過。
也可以使用兩個指針,先讓一個走n步,另一個接著走。那么當第一個指針達到鏈表尾部時候,第二個指針指向第n個節點。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode * p=head, *q=head;
int length=0;
while(p!=NULL)
{
p=p->next;
length++;
}
p=head;
if(n>length)
n=1;
else
n=length-n+1;
while(n-1>0&&p->next!=NULL)
{
q=p;
p=p->next;
n--;
}
if(q==p)
{
head=head->next;
}
else
{
q->next=p->next;
}
return head;
}