Created
January 24, 2020 18:19
-
-
Save susanhsrestha/1e93413cfdc5de12856f92082e447a41 to your computer and use it in GitHub Desktop.
This is an implemantation of Reversal of a singly linked list using recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Implementation of Linked List and Insertion of Elements | |
#include<iostream> | |
using namespace std; | |
struct Node{ | |
int data; // representation of list | |
Node* next; | |
}; | |
struct Node* head; | |
void display(){ | |
Node* temp = head; | |
cout<<"LIST : "; | |
while(temp!=NULL){ | |
cout<<temp->data<<" "; | |
temp = temp->next; // list traversal | |
} | |
cout<<endl; | |
} | |
void insertAtHead(int x){ | |
Node* temp = new Node; //creation of a node | |
temp->data = x; | |
if(head == NULL){ | |
temp->next = NULL; | |
head = temp; | |
display(); | |
} | |
else{ | |
temp->next = head; | |
head = temp; | |
} | |
display(); | |
} | |
void insertAtTail(int x){ | |
Node* temp = new Node; | |
temp->data = x; | |
temp->next = NULL; | |
Node* temp1 = head; | |
while(temp1->next!=NULL){ | |
temp1 = temp1->next;// link traversal | |
} | |
temp1->next = temp; | |
display(); | |
} | |
void insertAtN(int x, int n){ | |
Node* temp = new Node; | |
temp->data = x; | |
temp->next = NULL; | |
if(n == 1){ | |
temp->next = head; | |
head = temp; | |
display(); | |
} | |
else{ | |
Node* temp1 = head; | |
for(int i=0; i<n-2; i++){ | |
if(temp1->next == NULL){ | |
cout<<"Position can't be found and element can't be added"<<endl; | |
return; | |
} | |
temp1 = temp1->next; | |
} | |
temp->next = temp1->next; | |
temp1->next = temp; | |
} | |
display(); | |
} | |
void reverseLinkedList(Node* a){ | |
if(a->next == NULL){ | |
head = a; | |
return; | |
} | |
reverseLinkedList(a->next); | |
Node *b = a->next; | |
b->next = a; | |
a->next = NULL; | |
} | |
int main(){ | |
head = NULL; // empty list creation | |
insertAtHead(4); | |
insertAtHead(8); | |
insertAtTail(5); | |
insertAtN(3,1); | |
insertAtN(4,2); | |
insertAtN(2,6); | |
insertAtN(4,7); | |
reverseLinkedList(head); | |
display(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment