栈是一种只允许在一端进行插入和删除操作的线性表。在栈中,进行操作的一端叫做栈顶,相应地,另一端称为栈底。
下面举一个简单的实例去理解对栈的操作:从键盘上输入一组数,然后按相反的顺序输出到屏幕上。
/*
2017年10月20日22:19:58
目的;创建一个简单的栈,从键盘上输入一组正数,然后按相反的顺序输出。
*/
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct node)
#define TRUE 1
#define FALSE 0
typedef struct node
{
int data;
struct node *next;
} Stack;
int main()
{
//函数声明
void StackInit(Stack *top);
int IsEmpty(Stack *top);
int Push(Stack *top, int x);
int Pop(Stack *top, int *x);
//变量定义
int x;
Stack *top;
int i = 1;
top = (Stack *)malloc(LEN);
StackInit(top); //栈初始化
printf("Enter some positive integers:\n");
scanf("%d", &x); //输入结束标志为输入了小于等于0的数
while(x > 0) //入栈
{
Push(top, x);
scanf("%d", &x);
}
while(Pop(top, &x)) //出栈,只要栈顶指针不为空,继续循环
{
printf("%d\t", x);
if(i % 5 == 0) //一行5个元素
{
printf("\n");
}
i ++;
}
printf("\n");
return 0;
}
//栈初始化函数定义
void StackInit(Stack *top)
{
top->next = NULL;
}
//判断栈是否为空函数声明
int IsEmpty(Stack *top)
{
if(top->next == NULL)
return TRUE;
else
return FALSE;
}
//进栈函数定义
int Push(Stack *top, int x)
{
Stack *p;
p = (Stack *)malloc(LEN); //创建新节点
if(p == NULL)
{
return FALSE;
}
p->data = x;
p->next = top->next;
top->next = p; //栈指针后移
return TRUE;
}
//出栈函数定义
int Pop(Stack *top, int *x)
{
Stack *p;
if( IsEmpty(top) ) //判断栈是否为空
return FALSE;
p = top->next; //p指向栈顶后的一个节点
*x = p->data; //弹出数据元素
top->next = p->next; //栈顶指针前移
free(p); //释放内存空间
return TRUE;
}
/*
2017年10月20日22:50:40
在Code::Blocks中的输出结果为:
Enter some positive integers:
1 2 3 4 5 6 7 8 9 10 0
10 9 8 7 6
5 4 3 2 1
Process returned 0 (0x0) execution time : 14.118 s
Press any key to continue.
心得:栈与链表比较类似,比链表简单,至于其具体应用场合有哪些,还需要时间去学习。
*/