注:此文章来自“优快云”博主,仅在此借鉴,学习
各种基本算法实现小结(二)—— 堆 栈
(均已测试通过)
==============================================================
栈——数组实现
测试环境:Win - TC
- #include <stdio.h>
- char stack[512];
- int top=0;
- void push(char c)
- {
- stack[top]=c;
- top++;
- }
- char pop()
- {
- top--;
- return stack[top];
- }
- int is_empty()
- {
- return 0==top;
- }
- void main()
- {
- push('1');
- push('2');
- push('3');
- push('4');
- push('5');
- while(!is_empty())
- putchar(pop());
- putchar('/n');
- getch();
- }
运行结果:
====================================================
栈——数组实现2
测试环境:Win - TC
- #include <stdio.h>
- #include <malloc.h>
- /* typedef int DataType; */
- #define DataType int
- #define MAX 1024
- typedef struct
- {
- DataType data[MAX];
- int top;
- }stack, *pstack;
- pstack *init_stack()
- {
- pstack ps;
- ps=(pstack)malloc(sizeof(stack));
- if(!ps)
- {
- printf("Error. fail malloc.../n");
- return NULL;
- }
- ps->top=-1;
- return ps;
- }
- int empty_stack(pstack ps)
- {
- if(-1 == ps->top)
- return 1;
- else
- return 0;
- }
- int push(pstack ps, DataType data)
- {
- if(ps->top == MAX-1)
- {
- printf("Stack is full.../n");
- return 0;
- }
- ps->top++;
- ps->data[ps->top]=data;
- return 1;
- }
- int pop(pstack ps, DataType *data)
- {
- if(empty_stack(ps))
- {
- printf("Stack is empty.../n");
- return 0;
- }
- *data=ps->data[ps->top];
- ps->top--;
- return 1;
- }
- DataType top_stack(pstack ps)
- {
- if(empty_stack(ps))
- {
- printf("Stack is empty.../n");
- return 0;
- }
- return ps->data[ps->top];
- }
- void display(pstack ps)
- {
- int i;
- if(empty_stack(ps))
- {
- printf("Stack is empty.../n");
- return;
- }
- printf("printf the items of stack.../n");
- for(i=ps->top;i>-1;i--)
- printf("%4d", ps->data[i]);
- printf("/n/n");
- }
- void main()
- {
- int i, num, data, *pdata;
- pstack ps;
- ps=init_stack();
- printf("Enter stack num:");
- scanf("%d", &num);
- for(i=0;i<num;i++)
- {
- scanf("%d", &data);
- push(ps, data);
- }
- display(ps);
- printf("Top is %d/n/n", top_stack(ps));
- for(i=0;i<num;i++)
- {
- pop(ps, pdata);
- printf("%3d", *pdata);
- }
- printf("/n/n");
- display(ps);
- getch();
- }
运行结果:
====================================================
栈——链表实现
测试环境:Win - TC
- #include <stdio.h>
- #include <malloc.h>
- typedef char DataType;
- struct _node
- {
- DataType data;
- struct _node *next;
- };
- typedef struct _node node, *pstack;
- pstack init_stack()
- {
- pstack ps;
- ps=(pstack)malloc(sizeof(node));
- if(NULL == ps)
- {
- printf("Error. malloc is fail.../n"); 再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.youkuaiyun.com/jiangjunshow