-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSLL_CRUD.cpp
143 lines (137 loc) · 2.75 KB
/
SLL_CRUD.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node()
{
Node(0);
}
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
class Singlylinkedlist
{
public:
Node * head;
Singlylinkedlist()
{
this->head =nullptr;
}
void insert(int pos,int data)
{
Node * newnode = new Node(data);
Node *p =head;
if(pos==0)
{
if(head==nullptr)
{
head=newnode;
}
else
{
newnode->next = head;
head=newnode;
}
}
else if(pos>0)
{
for(int i=0;i<pos-1;i++)
{
p=p->next;
}
newnode->next=p->next;
p->next=newnode;
}
}
void insertatlast(int data)
{
Node* newnode =new Node(data);
if(head==NULL)
{
head=newnode;
}
else
{
Node *p=head;
while(p->next!=NULL)
{
p=p->next;
}
p->next=newnode;
}
}
void insertSortedLL(int x)
{
Node* p=head;
Node*q =NULL;
Node* newnode = new Node(x);
if(head==NULL)
{
head = newnode;
}
while(p!=NULL && p->data<x)
{
q=p;
p=p->next;
}
if(p==head)
{
newnode->next=head;
head=newnode;
}
else
{
newnode->next=q->next;
q->next=newnode;
}
}
int getsize()
{
Node*p=head;
int size=0;
while(p!=NULL)
{
size++;
p=p->next;
}
return size;
}
void printlist()
{
if(head==NULL)
cout<<"Linked list is empty"<<endl;
Node *p=head;
while(p!=NULL)
{
cout<<p->data<<"->";
p=p->next;
}
cout<<"\n";
}
};
int main()
{
Singlylinkedlist sll;
sll.insert(0,5);
sll.insert(0,6);
sll.insert(1,7);
for(int i=5;i>=1;i--)
{
sll.insert(0,i);
}
sll.printlist();
sll.insertatlast(4);
for(int i=3;i>0;i--)
{
sll.insertatlast(i);
}
sll.printlist();
cout<<sll.getsize();
return 0;
}