什麼?!不需要去在意它是倒數第幾個, 是這個意思嗎?!雖然覺得pointer 應該真的有懂, 但是好多小地方沒有考慮到喔QQ (會不會這就叫做沒有懂XD) 我好笨QQ
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
int length =0;
struct ListNode *p,*tmp;
p=head;
while (p!=NULL)
{
tmp=p->next;
p=tmp;
length++;
}
if (length==1)
return NULL;
if (length == n)
{
p=head->next;
head->next = NULL;
head = p;
return head;
}
int count = length -n-1;
int i=0;
for(p=head; i<length;i++)
{
if(i==count)
{
tmp = p->next;
if(tmp->next !=NULL)
{
p->next = tmp->next;
tmp->next = NULL;
tmp=p->next;
p=tmp;
}
else
{
p->next = NULL;
break;
}
i++;
}
else
{
tmp = p->next;
p= tmp;
}
}
return head;
}
看到別人的寫法覺得好驚人喔!這就是天才與笨蛋Q的差異吧哈哈哈哈哈
其實沒有把數字印出來真的看不懂!
用兩個pointer , 一個先往前move 到要倒數的個數, 然後再讓target (也就是pointer 會在前一個?!)指向head, 再兩個人一路往後!當走的比較快的那個走到底的時候, target 就可以把next 指到自己的next又next 去delete 掉下一個了!是一個用pointer 當index 的概念
太強大了吧QQ 而且好精簡QQ 但是寫code的時候這樣寫, 不印出來的話根本不知道在幹嘛啊QQ
(該不會只有我需要印出來?!XD)
(下面這是別人的厲害code QQ)
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
struct ListNode* target = head;
struct ListNode* temp = head;
for(int i = 1; i <= n; i++)
temp = temp->next;
if(!temp)
return target->next;
while(temp->next)
{
target = target->next;
temp = temp->next;
}
target->next = target->next->next;
return head;
}
沒有留言:
張貼留言