Thursday, 27 December 2012

Reverse a linked List in C++

This is a simple c++ code for reversing a single linked list.

#include<iostream.h>


class Node{
public:

Node* next;
int data;
};

Node* addToList(Node* head, int val)
{
Node *temp= head;
if(head == NULL)
{
head = new Node;
head->data = val;
head->next = NULL;
return head;
}
while(temp->next != NULL)
temp=temp->next;

Node *temp1=new Node;
temp1->data = val;
temp1->next = NULL;

temp->next = temp1;
return head;

}

void printList(Node* head)
{
Node * temp = head;

while(temp)
{
cout<<temp->data<<endl;
temp = temp->next;
}

}

//Reverse complete list.
Node* reverse(Node* head)
{

Node* temp = NULL;
Node* temp1 = NULL;


while(head)
{
temp = head;

head=head->next;

temp->next = temp1;

temp1=temp;

}
return temp;
}

//Reverse n nodes from the begining
Node* reverse(Node* head, int n)
{

Node* temp = NULL;
Node* temp1 = NULL;
Node *link = head;

int i=0;

while(head && i < n)
{
temp = head;
head = head->next;
temp->next = temp1;
temp1=temp;
i++;


}
//join the reversed list with new list
link->next = head;

return temp;
}


int main()
{

Node *head = NULL;

char choice = 'a';

int val =0;

cout<<"Enter the list value :"<<endl;

while(choice != 'b')
{

cin>>val;
cout<<"Enter choice "<<endl;
cin>>choice;

head = addToList(head,val);
}

cout<<" Print List :"<<endl;

printList(head);

head = reverse(head);

cout<<" Reverse printing :"<<endl;
printList(head);

head = reverse(head,3);

cout<<"Reverse n nodes :"<<endl;
printList(head);

return 0;
}


No comments:

Post a Comment

AWS Data Pipeline Services

https://www.youtube.com/watch?v=tykcCf-Zz1M