[問題] Leetcode#19 - 指標在linked list的使用

作者: donface ( v)   2018-09-12 01:08:40
開發平台(Platform): (Ex: Win10, Linux, ...)
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
Leetcode
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
題目是Leetcode#19- Remove Nth Node From End of List
https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
Given a linked list, remove the n-th node from the end of list and return its
head.
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.
程式碼是網路上看的解法,
這邊應該是我對指標的觀念不清楚
一開始temp_head and result_head 都指向了 head.
使用temp_head將長度算出, 這時候若印出temp_head應該會是 []
接著result_head用來找到倒數第N個數字. 找到後執行:
result_head->next=result_head->next->next;
這邊不能理解的, 這時候跳掉的應該是result_head, 這時候若是return result_head,
印出來的會是 [3 5]
為什麼最終return head 可以得到result_head跳掉的答案.
若是因為result_head指向head, 所以可以得到這個操作的結果. 為啥一開始用temp_head
算長度時.
不會造成head 指向尾端的NULL,
不好意思, 可能我對指標觀念還不是很正確, 描訴的可能不是很好. 請大家不吝解答.
餵入的資料(Input):
head=[1,2,3,4,5]
n=2
預期的正確結果(Expected Output):
錯誤結果(Wrong Output):
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
int i=0;
int len=0;
struct ListNode* temp_head =head;
struct ListNode* result_head =head;
while(temp_head != NULL) {
len++;
temp_head=temp_head->next;
}
return temp_head;
if (len==1)
return NULL;
while(i<len-n-1){
result_head=result_head->next;
i++;
}
if ((len-n) == 0)
head=head->next;
else
result_head->next=result_head->next->next;
return head;
}
補充說明(Supplement):
作者: achicn3 (Sher)   2018-09-12 02:26:00
作者: cphe (魔鬼藏在垃圾筒裡)   2018-09-12 08:38:00
有點看不懂你想表達的問題...另外為什麼while下面有個return你這邊的head result_head是不一樣的東西,head一直就指向head沒有改變,你移除第一個以外的node,head一樣是同一個。另外你是想問為什麼temp_head改變為什麼head不會改變嗎?如果是的話,因為他們就是不同的變數,除非你改變的是*temp_head,變數裡面存的就只是位址

Links booklink

Contact Us: admin [ a t ] ucptt.com