//C语言模拟栈,简单实现
#include <stdio.h>
#include <stdlib.h>
typedef struct Node node;
struct Node
{
int data;
node *next;
};
int quchu(node *p) //取出栈中的数
{
if (p->next == NULL)
return -1;
else
{
int x = p->next->data;
return x;
}
}
node *QC(node *p) //去除已经取出的数
{
node *L = p->next;
p->next = L->next;
free(L); //释放空间
L = NULL; //防止野指针
return p;
}
node *insert(int data, node *p) //插入元素
{
node *L = (node *)malloc(sizeof(node));
L->data = data;
L->next = p->next;
p->next = L;
return p;
}
int main()
{
int n, num;
node *head = (node *)malloc(sizeof(node));
head ->next = NULL;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &num);
head = insert(num, head);//插入
}
for (int i = 1; i <= n; i++)
{
int x = quchu(head);//取出
if (x != -1)//如果返回-1,说明栈中没有元素
head = QC(head);//去除
printf("%d\n", x);//打印元素
}
return 0;
}
04-02
615
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-29
868
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-19
1513
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)