Created
January 24, 2020 18:04
-
-
Save susanhsrestha/52089e44a49415f08d39a38c39281e8f to your computer and use it in GitHub Desktop.
This is an implementation of reversal of a Linked List
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 *current, *next, *prev; | |
current = head; | |
prev = NULL; | |
while(current != NULL){ | |
next = current->next; | |
current->next = prev; | |
prev = current; | |
current = next; | |
} | |
head = prev; | |
display(); | |
} | |
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment