-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathW2_DoubleLinkedList.cpp
148 lines (136 loc) · 3.1 KB
/
W2_DoubleLinkedList.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
// Created by dongwan-kim on 2022/04/11.
#include<iostream>
#include<string>
using namespace std;
class Node{
public:
Node *pre;
Node *next;
int value;
Node(){
pre= nullptr;
next= nullptr;
value=0;
}
};
class DoubleLinkedList{
public:
Node *head;
Node *tail;
int listSize;
DoubleLinkedList(){
head=tail= nullptr;
listSize=0;
}
bool empty(){
if(listSize==0)
return true;
else
return false;
}
void print(){
if(empty())
cout<<"empty"<<endl;
else{
Node *curNode = head;
for(int i=0;i<listSize;i++){
cout<<curNode->value<<" ";
curNode=curNode->next;
}
cout<<endl;
}
}
void Append(int v){
Node *newNode=new Node;
newNode->value=v;
if(empty()){
head=tail=newNode;
}
else {
tail->next = newNode;
newNode->pre = tail;
tail = newNode;
}
listSize++;
print();
}
int Delete(int idx){
if(empty()||idx>=listSize){
return -1;
}
Node* deleteNode=head;
if(idx==0){
if(listSize==1){
head=tail= nullptr;
}
else{
head=head->next;
head->pre= nullptr;
}
}
else{
for(int i=0;i<idx;i++){
deleteNode=deleteNode->next;
}
if(deleteNode==tail){
tail=deleteNode->pre;
tail->next= nullptr;
}
else {
deleteNode->pre->next = deleteNode->next;
deleteNode->next->pre = deleteNode->pre;
}
}
int k=deleteNode->value;
delete deleteNode;
listSize--;
return k;
}
void print_reverse(){
if(empty())
cout<<"empty";
Node *curNode=tail;
for(int i=0;i<listSize;i++){
cout<<curNode->value<<" ";
curNode=curNode->pre;
}
cout<<endl;
}
void max(){
if(empty())
cout<<"empty"<<endl;
Node *curNode=head;
int max=-1;
for(int i=0;i<listSize;i++){
if(curNode->value>max){
max=curNode->value;
}
curNode=curNode->next;
}
cout<<max<<endl;
}
};
int main() {
int m;
cin >> m;
DoubleLinkedList dl;
while (m--) {
string cmd;
cin >> cmd;
if (cmd == "Print") {
dl.print();
} else if (cmd == "Print_reverse") {
dl.print_reverse();
} else if (cmd == "Append") {
int a;
cin >> a;
dl.Append(a);
} else if (cmd == "Delete") {
int a;
cin >> a;
cout<<dl.Delete(a)<<endl;
} else if (cmd == "Max") {
dl.max();
}
}
}