顺序栈和链栈
2015-08-30 17:17
369 查看
顺序栈
#include <stdio.h> #include <stdlib.h> #define MAX 8 //顺序栈 typedef struct { int data[MAX]; int top; }SeqStack; void intiStack(SeqStack &S){ S.top=-1; } bool IsFull(SeqStack &S) { return (S.top == MAX-1) ? true:false; } bool IsEmpty(SeqStack &S) { return (S.top == -1) ? true:false; } void Push(SeqStack &S, int e) { if( IsFull(S) ) { printf("The stack is full, failed to push!\n"); return; } S.data[++S.top] = e; } int Pop(SeqStack &S) { int temp; if( IsEmpty(S) ) { printf("The stack is empty, failed to pop!\n"); return NULL; } temp= S.data[S.top--]; return temp; } void print(SeqStack &S) { int temp = S.top; int i=0; if(IsEmpty(S)) { printf("The stack is empty!\n"); return; } printf("Print the stack:\n"); while( temp>=0 ) { printf("%d ", S.data[i]); i++; temp--; } printf("\n"); } void main() { SeqStack s; intiStack(s); Push(s,1); Push(s,9); Push(s,8); Push(s,1); Push(s,3); Push(s,1); Push(s,8); print(s); printf("Pop the top element: %d\n",Pop(s)); printf("Pop the top element: %d\n",Pop(s)); print(s); }链栈
#include <stdio.h> #include <stdlib.h> typedef struct StackNode { int data; StackNode *next; }StackNode; typedef struct{ StackNode *top; }LinkStack; //建立一个头结点,头结点next域为null void initStack(LinkStack &S){ S.top=(StackNode *)malloc(sizeof(StackNode)); S.top->next=NULL; } bool IsEmpty(LinkStack &S) { return S.top->next==NULL ? true:false; } void Push(LinkStack &S,int e) { StackNode *p=(StackNode *) malloc (sizeof(StackNode)); p->data = e; p->next = S.top->next; S.top->next = p; } int Pop(LinkStack &S) { StackNode *p; int temp; if(IsEmpty(S)) { printf("The stack is empty, failed to pop!\n"); return NULL; } p=S.top->next; temp=p->data; S.top->next=S.top->next->next; free(p); return temp; } void print(LinkStack &S) { StackNode *p; p=S.top->next; if(IsEmpty(S)) { printf("The stack is empty!\n"); return; } printf("Print the stack (from right to left):\n"); while(p) { printf("%d ", p->data); p=p->next; } printf("\n"); } void main() { LinkStack s; initStack(s); Push(s,1); Push(s,9); Push(s,8); Push(s,3); Push(s,5); print(s); printf("Pop the top element: %d\n",Pop(s)); print(s); }
相关文章推荐
- 一步一步学习安装Grunt前端自动化工具
- 将CachedRowSet中的数据转储到对象中
- taskset: 让进程运行在指定的CPU 上
- java中十进制转二进制转换函数
- sql2008安装教程 SQL Server 2008 R2 安装图解
- php基础随笔
- Dialog(对话框)
- Cocos2d-x从入门到精通第四课《Cocos2d-x中的FileUtils》
- HTML文件中文打开乱码的问题
- JMeter非GUI方式运行时动态设置线程组及传参
- 深入理解ServletRequest与ServletResponse
- mongo两级数组嵌套数据更新问题
- USACO-Section 2.1 The Castle(DFS)
- IOS 开发笔记——二维码的生成和扫描
- 如何 通过 powershell 管理 MySQL 数据表
- (4.3.1.10)文字随按压事件变色
- Codeforces 574B Bear and Three Musketeers
- jmeter while controller 条件的写法
- 面向对象知识点梳理(三)
- stm32 外部中断的使用(含实例)