Click here to Skip to main content
15,895,740 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello All,

There is a singly link list with n elements. Two pointers are pointing to the first node of link list.now question is

"How can one reverse the link without allocationg any extra memory?"

Please help.

Regards,
joy
Posted

Traverse the list and move the pointers.
Keep a reference to the "last" node, and copy the "next" node pointer into a temporary variable. Then set the "next" to the save "last" pointer value. Set the "last" to the current node, and move to the temporary saved value. When you get to the end, set the head to the old last (now first) node.

Try it on paper, it'll make more sense.
 
Share this answer
 
Without allocating *any* extra memory - I don't think it can be done (though I'm prepared to be disproven).

A very lightweight way to do
1. Get a pointer (c++) / object reference (c#) the first element
2. Move the element after the item in step 1 (don't move this pointer) to the start of the list - how to do this depends on the language you are using.
3. Repeat step 2 until there are no items after the pointer created in step 1.

This will reverse the list at the small cost of the pointer/object reference in step 1.

[Edit]
Fixed incorrect algorithm
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900