-
Notifications
You must be signed in to change notification settings - Fork 0
/
W2_SingleLinkedList1.cpp
170 lines (155 loc) · 3.39 KB
/
W2_SingleLinkedList1.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
//Created by dongwan-kim on 2022/04/11.
#include<iostream>
#include<string>
using namespace std;
class Node{
public:
Node *next;
int value;
Node() {
next = nullptr;
value = 0;
}
};
class SingleLinkedList{
public:
Node *head;
Node *tail;
int listSize;
SingleLinkedList(){
head= nullptr;
tail= nullptr;
listSize=0;
}
bool empty(){
if(listSize==0)
return true;
else
return false;
}
void print(){
Node *curNode = head;
if(empty()) {
cout << "empty";
}
else{
for(int i=0;i<listSize;i++){
cout<<curNode->value<<" ";
curNode=curNode->next;
}
cout<<endl;
}
}
void Append(int x){
Node *newNode=new Node;
newNode->value=x;
newNode->next= nullptr;
if(empty()){
head=tail=newNode;
}
else{
tail->next=newNode;
tail=newNode;
}
listSize++;
print();
}
int Delete(int idx){
if(empty()||idx>=listSize)
return -1;
Node *curNode=head;
if(idx==0){
if(listSize==1){
head=tail= nullptr;
}
else{
head=head->next;
}
}
else{
Node *preNode=head;
for(int i=1;i<idx;i++){
preNode=preNode->next;
}
curNode=preNode->next;
preNode->next = curNode->next;
if(curNode==tail) {
tail = preNode;
}
}
int k=curNode->value;
delete curNode;
listSize--;
return k;
}
void Insert(int idx, int v){
if(idx>listSize)
cout<<"Index error"<<endl;
else{
if(idx==listSize)
Append(v);
else if(idx==0){
Node *newNode=new Node;
newNode->value=v;
newNode->next=head;
head=newNode;
listSize++;
}
else{
Node *newNode=new Node;
newNode->value=v;
Node *curNode=head;
for(int i=1;i<idx;i++){
curNode=curNode->next;
}
newNode->next=curNode->next;
curNode->next=newNode;
listSize++;
}
print();
}
}
void sum(){
if(empty())
cout<<0<<endl;
else{
Node *curNode=head;
int sum=0;
for(int i=0;i<listSize;i++){
sum += curNode->value;
curNode=curNode->next;
}
cout<<sum<<endl;
}
}
};
int main(){
int m;
cin>>m;
SingleLinkedList sl;
while(m--){
string cmd;
cin>>cmd;
if(cmd=="Print"){
sl.print();
}
else if(cmd=="Append"){
int a;
cin>>a;
sl.Append(a);
}
else if(cmd=="Delete"){
int a;
cin>>a;
cout<<sl.Delete(a)<<endl;
}
else if(cmd=="Insert"){
int a,b;
cin>>a>>b;
sl.Insert(a,b);
}
else if(cmd=="Sum"){
sl.sum();
}
}
}