如何用C语言创建一个链栈,并进行操作

来源:百度知道 编辑:UC知道 时间:2024/05/29 02:29:36
链栈结点类型定义为:
typedef struct node
{
int data;
struct node *next;
}node_type;
2)编写进栈函数push
3)编写出栈函数pop
4)编写main函数,首先建立一空链栈;
调用进栈函数,将从键盘输入的数据元素逐个进栈,输入0结束;显示进栈后的数据元素;
调用两次出栈函数,显示出栈后的数据元素。

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("");<