Confusion in reversing a linked list through recursion? [duplicate]

余生长醉 提交于 2019-12-25 05:21:10

问题


Possible Duplicate:
Linked list recursive reverse

I searched my question on SO and got a link

recursion stack trace

I din't understand How the head_ref is Pointing to 4 there?

Could anyone help me to understand this?


回答1:


ok, first of all, it's 6 am here, and i couldn't sleep all night ... so this might be bullshit ;) ... but here we go:

the "magic" happens at recursiveReverse(&rest); ... the & says that the parameter is the address of rest ... since rest itself is a pointer, our param is a pointer to a pointer ...

when the function has finished, the pointer has been changed, and points to the first element of the reversed sub-list (which is the 4-Node) ...

EX:

so let's say we have our list 1 -> 2 -> 3 -> 4 and have called recursiveReverse(struct node** head_ref) with a pointer to a pointer to the 1-node as the head_ref parameter

so let's say head_ref is at a certain address (which i call A)

head_ref is a pointer to a pointer ... so the value at the address A is another address (let's call that B)

so the "thing" that is stored at B is a pointer ... so the value at B is also an address (let's call that address C)

finally the "thing" stored at C is our struct ...

now with this in mind, we make our first recursive call to recursiveReverse(struct node** head_ref) ... this time our parameter is &rest ... &rest is a pointer to a pointer to the 2-node...

let's have a closer look ... the value of &rest is an address ... (hard to guess, we call that D) ... the value at D is an address (the address of the 2-node) which we call E

after the recursive call has finished, the sub-list 2 -> 3 -> 4 has been reversed (4 -> 3 -> 2), and one of our addresses has been updated with a new value ... D has been updated, and no longer holds the address E, but the address of the 4-node (call that F if you want ...)

so now, we have the pointer "first" pointing to the 1-node which has its next-pointer still pointing at the 2-node... so with first->next->next = first, we correct the 2-nodes "next" pointer, to point at the 1-node ...

since the 1-node shall no longer point to the 2-node, we have first->next=NULL and now the complete list has been reversed ...

since we have no return value, we return our reversed list by the pointer to pointer parameter head_ref ... with *head_ref = rest

rest is a pointer ... it's located at address D ... the current value at D is F (address of the 4-node)

so we write the value of D (which is F, the address of the 4-node) to the Address B (which is *head_ref)

and that is how the pointer to the 4-node is returned



来源:https://stackoverflow.com/questions/12408178/confusion-in-reversing-a-linked-list-through-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!