-
Notifications
You must be signed in to change notification settings - Fork 0
/
code linked list
155 lines (155 loc) · 2.41 KB
/
code linked list
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/* Linked-List
implemantion for linked list using c++ */
#include<iostream>
using namespace std;
template<class type>
class node
{
public:
type data;
node *link;
};
template<class type>
class linkedList
{
node<type>* head, * tail;
int counter;
public:
linkedList()
{
head = tail = NULL;
counter = 0;
}
bool IsEmpty()
{
return (head == nullptr);
}
void InsertFirst(type e)
{
node<type>* newNode = new node<type>;
newNode->data = e;
newNode->link = nullptr;
if (IsEmpty())
{
head = tail = newNode;
}
else
{
newNode->link = head;
head = newNode;
}
counter++;
}
void InsertLast(type e)
{
node<type>* newNode = new node<type>;
newNode->data = e;
if (IsEmpty())
{
head = tail = newNode;
}
else
{
tail->link = newNode;
tail = newNode;
}
counter++;
}
void InsertPossition(type e , int poss)
{
node <type> *newNode = new node<type>;
newNode->data = e;
if (poss < 1 || poss > counter + 1)
{
cout << " INVLID POSSITION !!!" << endl;
return;
}
else if (poss == 1)
{
InsertFirst(e);
}
else if (poss == counter + 1)
{
InsertLast(e);
}
else
{
node<type>* current = head ;
int i = 1;
while (i != poss -1)
{
current = current->link;
i++;
if (i == poss - 1)
{
newNode->link = current->link;
current->link = newNode;
break;
}
}
counter++;
}
}
void Delet(type e)
{
if(IsEmpty())
{
cout << " THE LIST IS EMPTY !! " << endl;
}
bool found = false;
node<type>* current = head;
node<type>* preCurrent = NULL;
while (current != NULL && ! found)
{
if (current->data == e)found = true;
else
{
preCurrent = current;
current = current->link;
}
}
if (!found)
{
cout << " THE ITEM IS NOT IN THE LIST !!!" << endl;
return;
}
else
{
if (current == head)
{
head = current->link;
if (head == NULL)tail = nullptr;
delete current;
}
else
{
preCurrent->link = current->link;
if (current == tail)tail = preCurrent;
delete current;
}
counter--;
}
}
void display()
{
node <type>* temp = head;
while (temp != nullptr)
{
cout << temp->data << " ";
temp = temp->link;
}
}
};
int main()
{
// declare an object .....
linkedList<int> l;
// call functions from the class
l.InsertFirst(5);
l.InsertFirst(10);
l.InsertLast(4);
l.InsertLast(8);
l.InsertPossition(7, 3);
l.display();
return 0;
}