Possible Duplicate:
How to read a singly linked list backwards?
Reverse a LinkedList c++
How can I reverse
the elements of a connected list
without using arrays
(I have to use only pointers thats my problem).
Possible Duplicate:
How to read a singly linked list backwards?
Reverse a LinkedList c++
How can I reverse
the elements of a connected list
without using arrays
(I have to use only pointers thats my problem).
You need neither to swap node content or a stack. If you want to reverse a single-linked list just walk it with a pair of pointers plus on intermediate pointer within the iterative loop. Don't forget to update the head pointer when you're finished;
void reverse_list(node **head)
{
node *cur=NULL, *nxt=NULL;
if (!(head || *head || (*head)->next))
return;
nxt = *head;
while (nxt != NULL)
{
node *prv = cur;
cur = nxt;
nxt = nxt->next;
cur->next = prv;
}
*head = cur;
}
Assuming the list node is something like this:
typedef struct node
{
..data..
struct node *next;
} node;
and it is properly managed, then you invoke as such:
node *head = NULL;
...fill the list...
reverse_list(&head);
Treat the list like a stack, pop the elements off and push them into a new list.
Conside a list called lst
which allows us to move forward backward i.e it is doubly linked list
You can reverse the list lst
by simply swapping the content of the beginning and the end nodes
void reverse(lst *beg,lst *end)
{
lst temp;
while(beg!=end)
{
//swap the content of the nodes
*temp=*beg;
*beg=*end;
*end=*temp;
beg=beg->Next();//move to next node
end=end->prev();//move to previous node
}
}
OR
If its a singly linked list
,you can use stack
void reverse(lst* beg)
{
stack<lst*> stc;
lst* temp=beg;
lst* temp1=beg;
while(temp)//store pointers to lst nodes in stack
{
stc.push(temp);
temp=temp.Next();
}
while(temp1)//pop the stack by inserting it into list from beginning
{
*temp1=*stc.top();
temp1=temp1.Next();
stc.pop();
}
}