C语言实现栈
2014-12-23 12:24
239 查看
/*参考《数据结构与 算法分析:C语言描述》*/ #include<stdio.h> #include<stdlib.h> #ifndef __cplusplus #include<stdbool.h> /*包含bool、true*/ #endif //__cplusplus typedef char ElemType; typedef struct Stack{ ElemType data; struct Stack *next; }Stack,*pStack; /***************************************/ pStack CreateStack(void); void Push(pStack ,ElemType ); bool IsEmpty(pStack); void Pop(pStack ); int Top(pStack ); void MakeEmpty(pStack); /***************************************/ pStack CreateStack(void) { pStack S=(pStack)malloc(sizeof(Stack)); if(S==NULL) { printf("申请内存失败!\n"); return NULL; } S->next=NULL; return S; } void Push(pStack S,ElemType a) { pStack p=(pStack)malloc(sizeof(Stack)); if(p==NULL) { printf("申请内存失败!\n"); return; } p->data=a; p->next=S->next; S->next=p; } bool IsEmpty(pStack S) { if(S->next==NULL) { return true; } return false; } void Pop(pStack S) { if(IsEmpty(S)) { printf("错误:试图在空栈弹出元素!\n"); } else { pStack p=S->next; S->next=S->next->next; free(p); } } int Top(pStack S) { if(IsEmpty(S)) { printf("不能从空栈中获得元素\n"); return 0; } else { return S->next->data; } } void MakeEmpty(pStack S) { while(!(IsEmpty(S))) { Pop(S); } } int main(void) { pStack S; S=CreateStack(); char c; c=getc(stdin); while(c!='\n') { Push(S,c); c=getc(stdin); } while(!IsEmpty(S)) { printf("%c\n",Top(S)); Pop(S); } system("pause"); return 0; }
相关文章推荐
- OO in C(2): C语言的多态实现
- 用C语言实现参数个数可变的函数
- 链表的c语言实现(三)
- lzw压缩算法的c语言实现
- c语言中时间陷阱的实现
- DataStructure---LinkList 链表C语言实现代码
- 链表的c语言实现(四)
- 求{1,2,3,...m}的幂集之C语言实现
- C语言中的面向对象(2)-C语言的多态实现
- C语言使用openSSL库DES模块实现加密功能详解
- C语言实现MATLAB 6.5中M文件的方法
- 用C语言来实现hex文件到coe文件的转化[原创]
- 链表的c语言实现(二)
- 用C语言实现八数码问题
- 用C语言实现UCS-2和UTF-8之间的互相转化
- OO in C(2): C语言的多态实现
- 求住 谁能帮我用java或c语言 实现一下公式 任意输入数字可出结果~~
- 链表的C语言实现(五)
- 用c语言实现艺术清屏
- 用c语言实现文件拷贝