Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

linked lists

Status
Not open for further replies.

danny2785

Programmer
Jun 26, 2006
16
US
Can someone help me understand reversing a singly linked list without recursion?

struct node* result = NULL;
struct node* current = *headRef;
struct node* next;
while (current != NULL) {
next = current->next; // tricky: note the next node
current->next = result; // move the node onto the result
result = current;
current = next;
}


why does this work? Sorry this is probably easy but I just don't understand it conceptually.
 
Try drawing it out. Start with

HeadRef -> A -> B -> C -> D -> NULL

Just work through the code and work out where result, current and next point to on each statement.
 
Try drawing a picture or diagram of what the code is doing. Once you see a diagram of how it works, it'll probably make more sense.
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top