(2)栈的链式实现:建立一个链栈,依次将a,b,c,d入栈;出栈并输出出栈结点数据域的值;将f入栈;输出当前链栈中各结点的数据域的值;用c++写代码
时间: 2024-04-12 21:30:59 浏览: 85
好的,以下是栈的链式实现的代码:
```cpp
#include <iostream>
using namespace std;
class Node {
public:
char data;
Node* next;
Node(char element) {
data = element;
next = nullptr;
}
};
class Stack {
private:
Node* top;
public:
Stack() {
top = nullptr;
}
bool isEmpty() {
return top == nullptr;
}
void push(char element) {
Node* newNode = new Node(element);
newNode->next = top;
top = newNode;
}
char pop() {
if (isEmpty()) {
cout << "Stack is empty. Cannot pop element." << endl;
return '\0';
}
char poppedElement = top->data;
Node* temp = top;
top = top->next;
delete temp;
return poppedElement;
}
void display() {
cout << "Stack elements: ";
Node* temp = top;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
Stack stack;
stack.push('a');
stack.push('b');
stack.push('c');
stack.push('d');
cout << "Popped element: " << stack.pop() << endl;
stack.push('f');
stack.display();
return 0;
}
```
输出结果为:
```
Popped element: d
Stack elements: f c b a
```
希望对你有所帮助!如果还有其他问题,请随时提问。
阅读全文