-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleLinkedList.cpp
More file actions
131 lines (121 loc) · 2.69 KB
/
SingleLinkedList.cpp
File metadata and controls
131 lines (121 loc) · 2.69 KB
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
#include <cstdlib>
#include<stdio.h>
#include<iostream>
using namespace std;
class Node{
public:
Node *next;
int data;
Node(){
next=NULL;
data=0;
}
};
class MyList{
private:
Node *head;
int length;
public:
MyList(){
head=NULL;
length=0;
}
void append2(int data);
void delete4m(int data);
void incLength(){length++;}
void decLength(){length--;}
void getLength(){cout<<"Length is ="<<length<<endl;}
void displayList();
};
void MyList:: displayList(){
Node *temp=head;
if(temp==NULL){
cout<<"The List is Empty"<<endl;
}
else{
cout<<"\nThe List =\t";
while(temp!=NULL){
cout<<temp->data<<"\t";
temp=temp->next;
}
cout<<endl;
}
}
void MyList::append2(int d){
Node *n=new Node;
Node *temp=head;
if(head==NULL){
head=n;
head->data=d;
head->next=NULL;
incLength();
}
else{
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=n;
temp->next->data=d;
temp->next->next=NULL;
incLength();
}
}
void MyList::delete4m(int d){
Node *temp=head,*temp2=NULL;
if(head->data==d){
//delete the head
head=temp->next;
delete(temp);
decLength();
}
else{
// delete from other places
while(temp->next!=NULL){
if(temp->next->data==d){
//need to delete this node
temp2=temp;
temp->next=temp->next->next;
delete temp2;
decLength();
break;
}
temp=temp->next;
}
}
}
/*int main(int argc, char** argv) {
int choice =0;
MyList obj;
int data;
while (choice!=10){
cout<<"Enter 1) Append to list 2) Delete from list 3) Length Of List 4) Display the list 10) Exit"<<endl;
cin>>choice;
switch(choice){
case 1:
{
cout<<"Enter the data to append"<<endl;
cin>>data;
obj.append2(data);
break;
}
case 2:
{
cout<<"Enter the data to delete"<<endl;
cin>>data;
obj.delete4m(data);
break;
}
case 3:
{
obj.getLength();
break;
}
case 4:
{
obj.displayList();
break;
}
}
}
return 0;
}*/