forked from tanus786/CP-Codes-HackOctober-Fest-2023
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLinked list. Cpp
110 lines (99 loc) · 1.51 KB
/
Linked list. 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
#include<iostream>
using namespace std;
class Node{
public:
int val;
Node *next;
Node(int val)
{
this->val=val;
this->next=nullptr;
}
};
class customlinkedlist {
public:
Node *head , *tail;
int size=0;
customlinkedlist(){
size=0;
head=nullptr;
tail=nullptr;
}
void addlast(int value){
Node *node=new Node(value);
if(size==0){
size++;
head=node;
tail=node;
return;
}
tail->next=node;
tail=node;
size++;
}
void addfirst(int value){
Node *node=new Node(value);
if(size==0){
addlast(value);
return;
}
node->next=head;
head=node;
size++;
}
void removelast(){
if(size==0){
cout<<"linked list is empty"<<endl;
return;
}
if(size==1)
{
size--;
head=nullptr;
tail=nullptr;
return;
}
size--;
Node *p=head;
while (p->next!=tail)
{
p=p->next;
}
p->next=nullptr;
tail=p;
}
void removefirst(){
if(size==0){
removelast();
return;
}
if(size==1){
removelast();
}
size--;
head=head->next;
}
void display(){
Node *p=head;
while (p!=nullptr)
{
cout<<p->val<<" ";
p=p->next;
}
cout<<endl;
}
};
int main(){
customlinkedlist *c1=new customlinkedlist();
c1->addlast(10);
c1->addlast(20);
c1->addlast(30);
c1->addlast(50);
c1->display();
c1->addfirst(80);
c1->display();
c1->removelast();
c1->display();
c1->removefirst();
c1->display();
}