[问题] 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