链栈
作者:
阿飞大魔王
,
2024-07-28 21:11:10
,
所有人可见
,
阅读 9
#include<bits/stdc++.h>
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 x)
{
Node* node=new Node(x);
node->next=dummy->next;
dummy->next=node;
}
void pop(Node* dummy)
{
dummy->next=dummy->next->next;
}
int top(Node* dummy)
{
return dummy->next->val;
}
void print(Node* dummy)
{
while(!empty(dummy))
{
cout<<top(dummy)<<' ';
pop(dummy);
}
}
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;
}