Geekpedia Programming Tutorials






Reverse a linked list

This code shows the logic behind reversing a linked list in C++ using pointers and looping through the current nodes, changing the order in which the elements are linked to eachother.

On Tuesday, November 6th 2007 at 11:20 PM
By Andrew Pociu (View Profile)
***--   (Rated 2.8 with 4 votes)
Contextual Ads
More C++ Resources
Advertisement
  1. NodePtr revList = NULL
  2. NodePtr currNode = currHead;
  3.  
  4. while(currNode != NULL)
  5. {
  6.         // Set the head to the next node
  7.         currHead=currHead->next;
  8.        
  9.         // Link currNode to the reversed list
  10.         currNode->next=revList;
  11.         revList=currNode;
  12.        
  13.         // Move currNode to next node
  14.         currNode=currHead;
  15.         currHead=revList;
  16. }
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this code snippet
Comment Current Comments
by deivapalan on Monday, November 12th 2007 at 08:32 PM

//set head to next node

currHead = currNode->next

is correct way.

by Nimesh on Thursday, April 10th 2008 at 08:15 PM

void linklist::reverse()
{
node *curr = p, *prev = NULL, *nxt_fwd = NULL;
//p is header
while(curr)
{
nxt_fwd = curr->link;
curr->link = prev;
prev =curr;
curr=nxt_fwd;
}
p = prev; /*save the new head */

}

by Cfir on Tuesday, July 21st 2009 at 04:52 PM

currHead=revList;
it's need to be outside the while

by newbie on Tuesday, August 18th 2009 at 12:59 PM

I think this is a working recursive solution:

Node * reverse(Node* previous=NULL, Node* head, Node* next)
{
head->child = previous
if(next==NULL)
return head;
else
return reverse(head,next,next->child);
}



by master on Wednesday, September 30th 2009 at 08:57 AM

i have to study ,......

by vinay on Friday, November 13th 2009 at 05:08 AM

HELLO HELLO HELLO !!!
The coding given at the top(by the site owner) is completely incorrect.
Anyone can dry-run it and find that it will not work.

by cfir on Thursday, November 19th 2009 at 11:59 AM

well it's worked withe my correction ,U probably have some other problem.

by ganzela on Friday, March 12th 2010 at 11:07 PM

it is a chuss tatorial.chuss e oyeeeeeeeeeeeeee


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Source Code
There is no related code.

Comment Related Tutorials
There are no related tutorials.

Jobs C++ Job Search
My skills include:

Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons