Reverse a singly linked list(iteratively)

What is the most efficient method to reverse a Singly Linked List? 
Iterative solution:

C++:
01 Node* reverse_iterative(Node* head)
02 {
03     if(head==NULL)
04         return NULL;
05     Node *prv=head;
06     Node *p=head->next;
07     Node *tmp=NULL;
08     while(p!=NULL){
09         tmp=p->next;
10         p->next=prv;
11         prv=p;
12         p=tmp;
13     }
14     head->next=NULL;
15     return prv;
16 }
A better solution:
:
01 Node* reverse_iterative(Node* p)
02 {
03     Node *prv=NULL;
04     while(p!=NULL){
05         Node* tmp=p->next;
06         p->next=prv;
07         prv=p;
08         p=tmp;
09     }
10     return prv;
11 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

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 )

Google+ photo

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

Connecting to %s