栈
2015-11-05 12:05
267 查看
栈链式实现
#include<stdio.h> #include<stdlib.h> typedef int ElementType; struct node { ElementType data; struct node *pNext; }; typedef struct node Stack; Stack *CreateStack(void); void DisposeStack(Stack *L); int IsEmpty(Stack *L); Stack *Push(Stack *L, ElementType X); ElementType PopAndTop(const Stack *L); Stack *CreateStack(void) { Stack *p; p = (Stack *)malloc(sizeof(Stack)); if (p == NULL) return NULL; p->pNext = NULL; return p; } void DisposeStack(Stack *L) { Stack *ptemp = L; if (ptemp != NULL) { free(ptemp); ptemp = ptemp->pNext; } } int IsEmpty(Stack *L) { return (L->pNext == NULL); } Stack *Push(Stack *L, ElementType X) { if (L == NULL) return NULL; Stack *pNew = (Stack *)malloc(sizeof(Stack)); pNew->data = X; pNew->pNext = NULL; if (pNew == NULL) return NULL; pNew->pNext = L->pNext; L->pNext = pNew; return L; } ElementType PopAndTop( Stack *L) { if (IsEmpty(L) == 1) return 0; ElementType num; num = L->pNext->data; L->pNext = L->pNext->pNext; free(L->pNext); return num; } int main(void) { return 0; }
栈顺序实现
#include<stdio.h> #include<stdlib.h> typedef int ElementType; struct node{ int capacity; int TopOfStack; ElementType *Array; }; typedef struct node Stack; Stack *CreateStack(int maxsize); void Dispose(Stack *L); void show(Stack *L); int IsEmpty(Stack *L); int IsFull(Stack *L); void Push(Stack *L, ElementType X); ElementType PopAndTop(Stack *L); Stack *CreateStack(int maxsize) { Stack *ps; ps = (Stack *)malloc(sizeof(Stack)); if (ps == NULL) return NULL; ps->capacity = maxsize; ps->TopOfStack = -1; ps->Array = (ElementType*)malloc(sizeof(ElementType)*maxsize); if (ps->Array == NULL) return NULL; return ps; } void Dispose(Stack *L) { if (L == NULL) return; if (L->Array != NULL) free(L->Array); free(L); } void show(Stack *L) { if (L == NULL) return; int i = L->TopOfStack; while (i >=0) { printf("%d \n", L->Array[i]); i--; } } int IsEmpty(Stack *L) { return (L->TopOfStack == -1); } int IsFull(Stack *L) { return (L->TopOfStack == L->capacity); } void Push(Stack *L, ElementType X) { if (IsFull(L) == 1) return ; L->Array[++(L->TopOfStack)] = X; } ElementType PopAndTop(Stack *L) { if (IsEmpty(L) == 1) return 0; return (L->Array[(L->TopOfStack)--]); } int main(void) { Stack *L = CreateStack(20); Push(L, 2); Push(L, 3); Push(L, 4); Push(L, 5); Push(L, 6); show(L); printf("\n"); PopAndTop(L); show(L); system("pause"); return 0; }
相关文章推荐
- 在制作APP和作项目时网页加载不出来
- 工业CT检测技术
- div无法跟随内容的增加而拉伸
- DocumentInteraction Controllerl的使用
- js获取当前时间
- HPP——让所有中小企业拥有自己的APP
- JAVA字符串格式化-String.format()的使用
- Android开源项目--分类汇总
- Android studio 导入第三方库
- 安卓开发,实现简单音乐播放器
- MYSQL 删除外键
- Shiro案例---认证和授权
- 中子射线照相检测技术
- 循环语句的分类练习
- 线程学习
- [MacOS] 终端使用ssh时,中文乱码问题处理
- JSP基于JDBC的数据库连接类实例
- ECharts+百度地图网络拓扑应用
- 本地通知 UILocalNotification
- 几款好看的HTML按钮样式