[原]Reverse A Linked List
To reverse a linked list, we start from the head (in this essay we will use linked list without extra head node). One way is to use a stack, pushes all nodes started from head to the last one. Then pops all nodes and appends them to the reversed list. The way is simple but not straightforward. And it's not simple enough and occupies extra space. If the size of list is very large, the space efficiency is poor. Also the time consumed contains 1. traverse the whole list to push all nodes into stack, and 2. traverse the whole stack (which is the whole list, again) and construct the new list.
So we consider another way. Here we don't need any extra spaces and only need to traverse the list once. It can be demonstrated as following:
|prev |cur |next
v v v
--- --- --- ---
NULL | |-->| |-->| |-->...-->| |-->NULL
--- --- --- ---
I
3 5
2|prev |cur |next
v v v
--- --- --- ---
NULL<--| |<--| | | |-->...-->| |-->NULL
1 --- 4 --- --- ---
II
OK, let's check the code.
The definition of node:
|
|
Auxiliary function to append a node to the list and can be used to construct a new list:
|
|
Other functions such as insert a node are not listed here because they are not used.
As illustrate in the diagram above, 5 steps need to reverse 2 nodes:
|
|
Now we consider the recursive way:
|
|
It's easy to implement the reverse:
|
|
浙公网安备 33010602011771号