Skip to content

Commit 0fb69f6

Browse files
authored
Merge pull request #118 from kartikeysingh6/master
Added DoublyLinked List
2 parents 0fe4efb + 87e7783 commit 0fb69f6

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
class Node{
5+
public:
6+
int data;
7+
Node* prev;
8+
Node* next;
9+
};
10+
11+
Node* head=NULL; //initially head is null;
12+
13+
Node* MakeNewNode(int x) {
14+
Node* newNode= new Node(); //new operator creates memory space
15+
newNode->data=x;
16+
newNode->prev=NULL;
17+
newNode->next=NULL;
18+
return newNode;
19+
}
20+
21+
//Inserts a Node at head of doubly linked list
22+
void InsertAtHead(int x){
23+
Node* newNode=MakeNewNode(x);
24+
if(head == NULL){
25+
head = newNode;
26+
return;
27+
}
28+
head->prev=newNode;
29+
newNode->next=head;
30+
head=newNode;
31+
}
32+
33+
void InsertAtTail(int x){
34+
Node* temp=head;
35+
Node* newNode=MakeNewNode(x);
36+
if(head==NULL){
37+
head=newNode;
38+
return;
39+
}
40+
while(temp->next!=NULL)
41+
temp = temp->next; // Go To last Node
42+
temp->next = newNode;
43+
newNode->prev = temp;
44+
}
45+
46+
//prints all nodes starting from head till we find NULL
47+
void Print(){
48+
Node* temp=head;
49+
while(temp!=NULL){
50+
cout<<temp->data<<" ";
51+
temp = temp->next;
52+
}
53+
cout<<endl;
54+
}
55+
56+
//prints all nodes from last to head;
57+
void ReversePrint(){
58+
Node* temp=head;
59+
if(temp==NULL)
60+
return;
61+
62+
//going till we reach last
63+
while(temp->next!=NULL){
64+
temp=temp->next;
65+
}
66+
//now from last we go backwards
67+
while(temp!=NULL) {
68+
cout<<temp->data<<" ";
69+
temp=temp->prev;
70+
}
71+
cout<<endl;
72+
}
73+
74+
int main(){
75+
InsertAtTail(2);
76+
Print();
77+
InsertAtTail(4);
78+
Print();
79+
InsertAtHead(6);
80+
Print();
81+
InsertAtTail(8);
82+
Print();
83+
InsertAtTail(3);
84+
Print();
85+
InsertAtTail(1);
86+
Print();
87+
InsertAtHead(4);
88+
Print();
89+
ReversePrint();
90+
91+
return 0;
92+
}

0 commit comments

Comments
 (0)