wrote:
>>> >From your hints, i think of a solution where in the last_node->ptr is
>>> made to point to first node and this logic needs to be excecuted as
>>> many times as many as strlen(string). Is this the solution you meant or
>>> any other improvements are possible?
>> No, and yes.
>>
>> You are working too hard: There exists a much simpler
>> solution than those you seem to be thinking about.
>>
>
> Yeah, i think so, i just got a solution but i don't think it utilises
> your hints, it goes like this
>
> reverse(stuct list* node)
> {
> struct list* original_head = node;
> struct list* new_head = NULL;
> struct list* original_head_next = NULL;
>
> while(original_head != NULL)
> {
> original_head_next = original_head->ptr;
> origianl_head->ptr = new_head;
> new_head = original_head;
> original_head = original_head_next;
> }
>
> return(new_head);
>
> }
>
> Did you mean any other solution???
That's the one I meant, although I would have written it
with fewer auxiliary variables. One way to look at this
approach is to think of it as removing the first node from
the old list (hint #1) and pushing it onto the start of the
new list (hint #2), and repeating until the old list is empty.
Start:
old -> A -> B -> C ->|
new ->|
Step 1:
old -> B -> C ->|
new -> A ->|
Step 2:
old -> C ->|
new -> B -> A ->|
Step 3:
old ->|
new -> C -> B -> A ->|
Or, to relate it to another common experience: Hold a
deck of playing cards face down, and deal the cards one at
a time (still face down) onto a pile on the table in front
of you. How does the order of the cards in the dealt pile
relate to the order in the original deck?
--
Eric Sosman
lid