-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwo way linkedlist.cpp
108 lines (97 loc) · 1.94 KB
/
two way linkedlist.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <iostream>
using namespace std;
typedef struct ListNode
{
int data;
struct ListNode *prev, *next;
}*nodeptr;
nodeptr head=NULL, tail=NULL;
nodeptr ptr;
void addData(int item)
{
nodeptr newNode= new ListNode;
newNode->data=item;
newNode->next=NULL;
newNode->prev=NULL;
if(head==NULL)
{
head=newNode;
tail=newNode;
ptr=head;
}
else
{
newNode->prev=tail;
tail=newNode;
ptr->next=newNode;
ptr=newNode;
}
}
void displayFromFirst(nodeptr p)
{
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}
void displayFromLast(nodeptr p)
{
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->prev;
}
}
void insertMiddle(int node,int item, nodeptr p)
{
nodeptr curr;
nodeptr newNode= new ListNode;
newNode->data=item;
newNode->prev=NULL;
newNode->next=NULL;
while(p->data!=node && p->next!=NULL)
{
p=p->next;
curr=p->next;
}
if(p->data==node)
{
newNode->prev=p;
newNode->next=p->next;
p->next=newNode;
curr->prev=newNode;
}
else
{
cout<<"not found"<<endl;
}
}
int main()
{
int n, item,i,node;
cout<<"Enter number of nodes: ";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"Enter Item: ";
cin>>item;
addData(item);
}
cout<<"Displaying from First "<<endl;
displayFromFirst(head);
cout<<endl;
cout<<"Displaying from Last "<<endl;
displayFromLast(tail);
cout<<"After which node you want to insert: ";
cin>>node;
cout<<"Enter item: ";
cin>>item;
insertMiddle(node,item,head);
cout<<endl;
cout<<"Displaying from First "<<endl;
displayFromFirst(head);
cout<<endl;
cout<<"Displaying from Last "<<endl;
displayFromLast(tail);
}