-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linked.cpp
119 lines (99 loc) · 1.47 KB
/
Linked.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
109
110
111
112
113
114
115
116
117
118
119
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
class Linked
{
private:
Node *first;
public:
Linked(){this->first=NULL;}
~Linked();
int length();
void Display();
void Insert(int x,int pos);
};
Linked::~Linked()
{
Node *p=first;
while(first)
{
first=first->next;
delete p;
p=first;
}
}
void Linked::Insert(int x,int pos)
{
if(pos < 0 || pos > length())
return;
Node *temp=new Node;
temp->next=NULL;
temp->data=x;
if(pos==0)
{
temp->next=this->first;
this->first=temp;
}
else
{
Node *n=this->first;
for(int i=0 ; i < pos-1 ; i++ )
{
n=n->next;
}
temp->next=n->next;
n->next=temp;
n=NULL;
delete n;
}
}
int Linked::length()
{
Node *temp;
int len=0;
temp=this->first;
while(temp)
{
temp=temp->next;
len++;
}
temp=NULL;
delete temp;
return len;
}
void Linked::Display()
{
Node *temp=this->first;
while(temp)
{
cout<<"->"<<temp->data<< " ";
temp=temp->next;
}
cout<<endl;
}
int main()
{
Linked l;
int choice,n,k;
do
{
cout<<"enter your choice:\n1->Insert(element,posion)\n2->Display"<<endl;
cin>>choice;
switch(choice)
{
case 1: cout<<"\nenter element and position"<<endl;
cin>>n;
cin>>k;
l.Insert(n,k);
break;
case 2: l.Display();
break;
}
}while(choice > 0 || choice < 3);
return 0;
}