Created
July 7, 2018 16:32
-
-
Save miladabc/e72c37fe0049b8689c2650fa523f2d4e to your computer and use it in GitHub Desktop.
Doubly 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
//Milad Abbasi | |
//06-07-2018 | |
//Doubly Linked List | |
#include <iostream> | |
using namespace std; | |
class Node | |
{ | |
public: | |
int data; | |
Node *next; | |
Node *prev; | |
}; | |
class DoublyLinkedList | |
{ | |
Node *head; | |
Node *tmp; | |
public: | |
DoublyLinkedList() | |
{ | |
head = NULL; | |
} | |
void insertStart(int value) | |
{ | |
tmp = new Node; | |
tmp->data = value; | |
tmp->prev = NULL; | |
if(isEmpty()) | |
tmp->next = NULL; | |
else | |
tmp->next = head; | |
head = tmp; | |
} | |
void insertEnd(int value) | |
{ | |
tmp = new Node; | |
tmp->data = value; | |
tmp->next = NULL; | |
if(isEmpty()) | |
{ | |
tmp->prev = NULL; | |
head = tmp; | |
} | |
else | |
{ | |
Node *last = new Node; | |
last = head; | |
while(last->next != NULL) | |
last = last->next; | |
last->next = tmp; | |
tmp->prev = last; | |
} | |
} | |
void insertAfter(int pos, int value) | |
{ | |
tmp = new Node; | |
tmp->data = value; | |
if(isEmpty()) | |
{ | |
tmp->next = NULL; | |
tmp->prev = NULL; | |
head = tmp; | |
} | |
else | |
{ | |
Node *current = new Node; | |
current = head; | |
for(int i = 1; i < pos; i++) | |
current = current->next; | |
tmp->prev = current; | |
tmp->next = current->next; | |
if(current->next != NULL) | |
current->next->prev = tmp; | |
current->next = tmp; | |
} | |
} | |
void deleteStart() | |
{ | |
if(isEmpty()) | |
{ | |
cout<<"List is empty"; | |
return; | |
} | |
tmp = head; | |
head = head->next; | |
head->prev = NULL; | |
delete tmp; | |
} | |
void deleteEnd() | |
{ | |
if(isEmpty()) | |
{ | |
cout<<"List is empty"; | |
return; | |
} | |
tmp = head; | |
while(tmp->next != NULL) | |
tmp = tmp->next; | |
tmp->prev->next = NULL; | |
delete tmp; | |
} | |
void deletePosition(int pos) | |
{ | |
if(isEmpty()) | |
{ | |
cout<<"List is empty"; | |
return; | |
} | |
tmp = head; | |
for(int i = 1; i < pos; i++) | |
tmp = tmp->next; | |
tmp->prev->next = tmp->next; | |
tmp->next->prev = tmp->prev; | |
delete tmp; | |
} | |
bool isEmpty() | |
{ | |
return head == NULL; | |
} | |
void print() | |
{ | |
Node *tmp = new Node; | |
tmp = head; | |
while(tmp) | |
{ | |
cout<<tmp->data<<"\t"; | |
tmp = tmp->next; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment