Home > Uncategorized > Reversing a linked list

Reversing a linked list

So again, here is how you can reverse a singly-linked list :

reverse(struct node ** start)
{

struct node * prev = NULL;
struct node * curr = *start;

while(curr)
{

swap(&prev, &curr->next);
swap(&curr, &prev);

}
*start = prev;

}
and here is for a doubly-linked list :

reverse(struct node **start)
{

struct node *curr = *start;

while(curr)
{

swap(&curr->prev, &curr->next);
if(!curr->prev)

*start = curr;

curr = curr->prev;

}

}

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.