-
Notifications
You must be signed in to change notification settings - Fork 0
/
4_2.cpp
146 lines (136 loc) · 2.51 KB
/
4_2.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
#include<iostream>
using namespace std;
template<class T>
class Node {
public:
T data;
Node<T>* link;
};
template<class T>
class LinkedStack {
public:
template<class T>//重载输出运算符
friend ostream& operator<<(ostream& out, LinkedStack<T>&);
template<class T>//重载输入运算符
friend istream& operator>>(istream& in, LinkedStack<T>&);
LinkedStack() { top = 0; }
bool IsEmpty()const { return top == 0; }
T Top()const;//栈顶元素
LinkedStack<T>& Push(const T& x);//进栈
LinkedStack<T>& Pop(T& x);//出栈
LinkedStack<T>& Delete(const T& x);//删除元素
bool Find(const T& x)const;//查找元素
Node<T>* top;
};
template<class T>//重载输出运算符
ostream& operator<<(ostream& out, LinkedStack<T>& x)
{
while (!x.IsEmpty())
{
T temp;
x.Pop(temp);
out << temp;
if (!x.IsEmpty())
out << " ";
}
return out;
}
template<class T>
istream& operator>>(istream& in, LinkedStack<T>& x)
{
cout << "please input the number:";
int num;
in >> num;
for (int i = 0; i < num; i++)
{
T temp;
in >> temp;
x.Push(temp);
}
return in;
}
template<class T>//获取栈顶元素
T LinkedStack<T>::Top()const
{
return top->data;
}
template<class T>//进栈
LinkedStack<T>& LinkedStack<T>::Push(const T& x)
{
Node<T>* p = new Node<T>;
p->data = x;
p->link = top;
top = p;
return *this;
}
template<class T>//出栈
LinkedStack<T>& LinkedStack<T>::Pop(T& x)
{
x = top->data;
Node<T>* p = top;
top = top->link;
delete p;
return *this;
}
template<class T>//删除元素
LinkedStack<T>& LinkedStack<T>::Delete(const T& x)
{
Node<T>* current = top;
if (current->data == x)
{
top = top->link;
delete current;
}
else
{
Node<T>* temp = current;
current = current->link;
while (current)
{
if (current->data == x)
{
temp->link = current->link;
delete current;
return *this;
}
current = current->link;
temp = temp->link;
}
}
return *this;
}
template<class T>//查找元素
bool LinkedStack<T>::Find(const T& x)const
{
Node<T>* temp = top;
while (temp)
{
if (temp->data == x)
return 1;
temp = temp->link;
}
return 0;
}
template<class T>
void delete_all(LinkedStack<T>& s, const T& x)
{
while (s.Find(x))
{
s.Delete(x);
}
}
int main()
{
char x;
cin >> x;
LinkedStack<char>zqzy;
cin >> zqzy;
if (zqzy.IsEmpty())
{
cout << "empty stack!";
return 0;
}
delete_all(zqzy, x);
cout << zqzy;
return 0;
}