1 回答
TA贡献1880条经验 获得超4个赞
1 思路: 主要是链表的插入和删除操作
2 代码
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node_type;
void push(node_type* &stack, int elem){
node_type*node = (node_type*)malloc(sizeof(node_type));
node->data = elem;
node->next = stack;
stack = node;
}
int pop(node_type* &stack){
int elem = stack->data;
node_type*node = stack;
stack = stack->next;
free(node);
return elem;
}
bool IsEmpty(node_type* stack){
return stack == NULL;
}
void display(node_type*stack){
while (stack){
printf("%d ", stack->data);
stack = stack->next;
}
puts("");
}
void destroy(node_type*stack){
while (!IsEmpty(stack)){
pop(stack);
}
}
int main(){
puts("(1) 建立空链栈");
node_type*stack = NULL;
puts("\n(2) 调用进栈函数,将从键盘输入的数据元素逐个进栈,输入0结束;");
int num;
scanf("%d", &num);
while (num != 0){
push(stack, num);
scanf("%d", &num);
}
puts("\n(3) 显示进栈后的数据元素");
display(stack);
puts("\n(4) 调用两次出栈函数,显示出栈后的数据元素");
if (!IsEmpty(stack))
printf("%d\n", pop(stack));
if (!IsEmpty(stack))
printf("%d\n", pop(stack));
destroy(stack);
getchar();
getchar();
return 0;
}
3 运行效果
- 1 回答
- 0 关注
- 222 浏览
添加回答
举报