前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于栈的简单应用的小例子

关于栈的简单应用的小例子

作者头像
Reborn Lee
发布2020-06-29 11:45:07
8410
发布2020-06-29 11:45:07
举报
文章被收录于专栏:用户7494468的专栏

栈是一种只允许在一端进行插入和删除操作的线性表。在栈中,进行操作的一端叫做栈顶,相应地,另一端称为栈底。


下面举一个简单的实例去理解对栈的操作:从键盘上输入一组数,然后按相反的顺序输出到屏幕上。


/*

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.


心得:栈与链表比较类似,比链表简单,至于其具体应用场合有哪些,还需要时间去学习。

*/

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2017-10-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 FPGA LAB 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档