Skip to content

Instantly share code, notes, and snippets.

@miladabc
Created July 7, 2018 16:32
Show Gist options
  • Save miladabc/e72c37fe0049b8689c2650fa523f2d4e to your computer and use it in GitHub Desktop.
Save miladabc/e72c37fe0049b8689c2650fa523f2d4e to your computer and use it in GitHub Desktop.
Doubly Linked List
//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