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 derfloh 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
Joined
Jun 26, 2006
Messages
16
Location
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

Replies
1
Views
209
Replies
5
Views
348
  • Locked
  • Question Question
Replies
7
Views
333
Replies
14
Views
529
Replies
10
Views
814

Part and Inventory Search

Sponsor

Back
Top