0% found this document useful (0 votes)
30 views3 pages

Double Linked List

Uploaded by

Akmal Ramadhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views3 pages

Double Linked List

Uploaded by

Akmal Ramadhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <bits/stdc++.

h>
#define ll long long
using namespace std;

struct node{
int value;
node *next, *prev;
};

int listSize = 0;

node *head = NULL, *tail = NULL, *curr = NULL;

node* newNode(int x) {
node* newNode = (node*)malloc(sizeof(struct node));
newNode->value = x;
newNode->next = NULL;
newNode->prev = NULL;
listSize++;
return newNode;
}

void pushHead(int x) {
if(!head) {
head = tail = newNode(x);
return;
}
node *temp = newNode(x);
head->prev = temp;
temp->next = head;
head = temp;
return;
}

void pushTail(int x) {
if(!head) {
head = tail = newNode(x);
return;
}
node *temp = newNode(x);
temp->prev = tail;
tail->next = temp;
tail = temp;
return;
}

void pushMid(int index, int x){


if(!head || index==0){
pushHead(x);
return;
}
if(index == listSize) {
pushTail(x);
return;
}
curr = head;
for(int i = 0; i<index-1; i++){
if(curr == tail){
return;
}
curr = curr->next;
}
node *temp = newNode(x);
temp->next = curr->next;
curr->next->prev = temp;
curr->next = temp;
temp->prev = curr;
return;
}

int popHead() {
if(!head) {
return -1;
}
int ret = head->value;
curr = head;
head = head->next;
head->prev = NULL;
free(curr);
listSize--;
return ret;
}

int popTail() {
if(!head) {
return -1;
}
if(head == tail) {
popHead();
}
int ret;
ret = tail->value;
curr = tail;
tail->prev->next = NULL;
tail = tail->prev;
free(curr);
listSize--;
return ret;
}

void popMid(int index){


if(index==0){
popHead();
return;
}
if(index == listSize-1) {
popTail();
return;
}
curr = head;
for(int i = 0; i<index-1; i++){
if(curr == tail){
return;
}
curr = curr->next;
}
node *temp = curr->next;
curr->next = curr->next->next;
curr->next->prev = curr;
free(temp);
listSize--;
return;
}

void showLL() {
curr = head;
while(curr) {
cout << curr->value << " - ";
curr = curr->next;
}
cout << endl << listSize;
}

void showLLreverse() {
curr = tail;
while(curr) {
cout << curr->value << " - ";
curr = curr->prev;
}
}

int main() {
pushHead(1);
pushHead(6);
pushTail(2);
pushTail(5);
showLL();
cout << endl;
pushMid(4,3);
showLL();
cout << endl;
popMid(3);
showLL();
cout << endl;
showLLreverse();
}

You might also like