Skip to content

Commit 837b71a

Browse files
Merge pull request pranjay-poddar#183 from Saksham188/master
AddedDoublyLinkedList
2 parents 9d887f3 + e8b42b9 commit 837b71a

File tree

2 files changed

+118
-0
lines changed

2 files changed

+118
-0
lines changed

c++/DoublyLinkedList.cpp

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
///In this we have 2 pointers next and previous at every node.
5+
6+
class Node
7+
{
8+
public:
9+
int Data;
10+
Node* next;
11+
Node* prev;
12+
13+
Node(int Value)
14+
{
15+
Data= Value;
16+
next=NULL;
17+
prev=NULL;
18+
}
19+
};
20+
21+
///Here we are inserting at the head of Linked List.
22+
void InsertAtHead(Node* &head,int Value)
23+
{
24+
Node* n=new Node(Value);
25+
26+
n->next=head;
27+
if(head!=NULL) ///its because if head is null then we can't access its previous.
28+
{
29+
head->prev=n;
30+
}
31+
32+
head=n;
33+
}
34+
///Here we are inserting at the tail of Linked List.
35+
void InsertAtTail(Node* &head,int Value)
36+
{
37+
if(head==NULL)
38+
{
39+
InsertAtHead(head,Value);
40+
return;
41+
}
42+
Node* n= new Node(Value);
43+
44+
Node* temp=head;
45+
46+
while(temp->next!=NULL)
47+
{
48+
temp=temp->next;
49+
}
50+
temp->next=n;
51+
n->prev=temp;
52+
}
53+
///Here we are displaying complete Linked List.
54+
void Display(Node* head)
55+
{
56+
Node* n=head;
57+
58+
while(n->next!=NULL)
59+
{
60+
cout<<n->Data<<"->";
61+
n=n->next;
62+
}
63+
cout<<"NULL"<<endl;
64+
}
65+
///Here we are deleting at the head of Linked List.
66+
void DeleteAtHead(Node* &head)
67+
{
68+
Node* todelete=head;
69+
head=head->next;
70+
head->prev=NULL;
71+
72+
delete todelete;
73+
}
74+
75+
///Here we are deleting at particular position of Linked List.
76+
void Deletion(Node* &head,int pos)
77+
{
78+
if(pos==1)
79+
{
80+
DeleteAtHead(head);
81+
return;
82+
}
83+
Node* temp=head;
84+
int Count=1;
85+
while(temp!=NULL && Count!=pos)
86+
{
87+
temp=temp->next;
88+
Count++;
89+
}
90+
temp->prev->next=temp->next;
91+
92+
if(temp->next!=NULL)
93+
{
94+
temp->next->prev=temp->prev;
95+
}
96+
97+
98+
delete temp;
99+
}
100+
101+
102+
int main()
103+
{
104+
Node* head=NULL;
105+
InsertAtTail(head,1);
106+
InsertAtTail(head,2);
107+
InsertAtTail(head,3);
108+
InsertAtTail(head,4);
109+
InsertAtTail(head,5);
110+
Display(head);
111+
InsertAtHead(head,6);
112+
InsertAtHead(head,7);
113+
InsertAtHead(head,8);
114+
Display(head);
115+
116+
Deletion(head,1);
117+
Display(head);
118+
}

c++/DoublyLinkedList.exe

1 MB
Binary file not shown.

0 commit comments

Comments
 (0)