-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist.cpp
121 lines (117 loc) · 2 KB
/
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
109
110
111
112
113
114
115
116
117
118
119
120
121
#include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
class ll
{
Node *head=NULL;
public:
void addatEnd(int);
void traverse();
void addatStart(int);
void addatPosition(int,int);
void deleteatPosition(int);
void reversell();
};
void ll::addatEnd(int k)
{
Node* newNode=new Node();
newNode->data=k;
newNode->next=NULL;
if(head==NULL)
head=newNode;
else
{
Node *temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->next=newNode;
}
}
void ll::traverse()
{
Node* t;
t=head;
while(t!=NULL)
{
cout<<t->data<<" ";
t=t->next;
}
}
void ll::addatStart(int k)
{
Node* newNode=new Node();
newNode->data=k;
newNode->next=head;
head=newNode;
}
void ll::addatPosition(int n,int k)
{
Node* newNode=new Node();
newNode->data=k;
newNode->next=NULL;
if(n==1)
{
newNode->next=head;
head=newNode;
}
else
{
Node* tmp1=head;
for(int i=1;i<n-1;i++)
tmp1=tmp1->next;
newNode->next=tmp1->next;
tmp1->next=newNode;
}
}
void ll::deleteatPosition(int n)
{
Node *temp=head;
if(n==1)
{
head=temp->next;
delete temp;
}
else
{
for(int i=1;i<n-1;i++)
temp=temp->next;
Node* temp2=temp->next;
temp->next=temp2->next;
delete(temp2);
}
}
void ll::reversell()
{
Node *current=head,*nxt,*prev=NULL;
while(current!=NULL)
{
nxt=current->next;
current->next=prev;
prev=current;
current=nxt;
}
head=prev;
}
int main()
{
ll l;
l.addatStart(4);
l.addatEnd(5);
l.addatEnd(6);
l.traverse();
cout<<endl;
l.addatPosition(2,10);
l.addatPosition(1,12);
l.traverse();
l.deleteatPosition(2);
cout<<endl;
l.traverse();
l.reversell();
cout<<endl;
l.traverse();
}