Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Last active July 1, 2019 17:30
Show Gist options
  • Save manojnaidu619/ce02fda7ee9617e7abcf789f81b8255b to your computer and use it in GitHub Desktop.
Save manojnaidu619/ce02fda7ee9617e7abcf789f81b8255b to your computer and use it in GitHub Desktop.
Doubly linked list in CPP
#include <iostream>
using namespace std;
struct Node{
struct Node *prev;
int data;
struct Node *next;
}*start=NULL,*last=NULL;
void insert(int ele){
struct Node *p = start,*temp;
if(p==NULL){
temp = new Node;
temp->data = ele;
temp->prev = NULL;
temp->next = NULL;
start=last=temp;
}else{
temp = new Node;
temp->data = ele;
temp->next = last->next;
last -> next = temp;
temp->prev = last;
last = temp;
}
}
void display(){
struct Node *p = start;
while(p){
cout << p->data << " == ";
p=p->next;
}
}
int count(){
int count = 0;
struct Node *p = start;
while(p){
count++;
p=p->next;
}
return count;
}
void insert_at_beg(int ele){
if(start==NULL){
insert(ele);
return;
}
struct Node *temp;
temp = new Node;
temp->data = ele;
temp -> next = start;
start -> prev = temp;
temp->prev = NULL;
start = temp;
}
void insert_at(int pos,int ele){
struct Node *p = start,*temp;
if(pos <= 1){
insert_at_beg(ele);
}
else if(pos > count()){
insert(ele);
}
else{
for(int i=1;i<pos-1;i++){
p=p->next;
}
temp = new Node;
temp->data = ele;
temp -> next = p->next;
p->next = temp;
temp -> prev = p;
}
}
void del_at(int pos){
struct Node *p = start,*q=NULL;
if(pos<1 || pos>count() || start==NULL){
cout << endl << "Not Possible!" << endl;
return;
}
if(pos == 1){
start = p->next;
p->next->prev = NULL;
delete p;
}
else if(pos < count()){
for(int i=1;i<=pos-1;i++){
q=p;
p=p->next;
}
q->next = p->next;
p->next->prev = q;
delete p;
}
}
int main(){
for(int i=1;i<=10;i++){
insert(i);
}
display();
del_at(3);
display();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment