链栈基本操作
作者:
三万岁_6
,
2024-07-29 00:05:31
,
所有人可见
,
阅读 2
#include <iostream>
using namespace std;
struct Node{
int val;
Node *next;
Node(int x): val(x), next(NULL){}
};
Node *init()
{
Node *dummy = new Node(-1);
return dummy;
}
bool empty(Node *dummy){
return dummy -> next == NULL;//链式存储只可能空,一般不可能满
}
void push(Node *dummy,int val){ //头插法
Node *node = new Node(val);
node -> next = dummy -> next;
dummy -> next = node;
}
void pop(Node *dummy){
Node *node = dummy -> next;
dummy -> next = node -> next;
delete node;
}
int top(Node *dummy){
return dummy -> next -> val;
}
void print(Node *dummy){
Node *p = dummy -> next;
while(p != NULL){
cout << p -> val << ' ';
p = p -> next;
}
}
int main()
{
// 测试链栈各操作
Node *dummy = init();
push(dummy, 1);
push(dummy, 2);
push(dummy, 3);
push(dummy, 4);
printf("栈顶元素:%d\n", top(dummy));
pop(dummy);
printf("栈顶元素:%d\n", top(dummy));
printf("栈是否为空:%d\n", empty(dummy));
print(dummy);
return 0;
}