堆栈的链式表示和实现
2014-09-27 23:04
204 查看
#include<iostream> using namespace std; typedef char DataType; //记得加分号 typedef struct snode { DataType x; struct snode *next; }SNode; void Initiate(SNode **head) { (*head)=(SNode*)malloc(sizeof(SNode)); (*head)->next=NULL; } //入栈 void StackPush(SNode *head,DataType x) { if(head==NULL) { cout<<"error"<<endl; return ; } SNode *p; p=(SNode*)malloc(sizeof(SNode)); p->x=x; p->next=head->next; head->next=p; } //出栈 DataType StackPop(SNode *head) { if(head->next==NULL) { cout<<"the stack is empty"<<endl; return NULL; } SNode *p; DataType d; p=head->next; d=p->x; head->next=p->next; free(p); return d; } //取得栈顶元素 DataType StackGet(SNode *head) { if(head->next==NULL) { cout<<"the stack is empty"<<endl; return NULL; } return head->next->x; } void Destroy(SNode *head) { SNode *p,*p1; p=head; while(p->next!=NULL) { p1=p; p=p->next; free(p1); } } int StackNotEmpty(SNode *head) { if(head->next==NULL) return 0; else return 1; } void main() { SNode *stack; Initiate(&stack); StackPush(stack,'x'); cout<<StackGet(stack)<<endl; StackPush(stack,'j'); StackPush(stack,'k'); cout<<StackPop(stack)<<endl; cout<<StackPop(stack)<<endl; cout<<StackPop(stack)<<endl; cout<<StackPop(stack)<<endl; //由于链式栈没有元素,所以输出空 if(StackNotEmpty(stack)) cout<<"Not empty"<<endl; else cout<<"empty!"<<endl; Destroy(stack); system("pause"); }
相关文章推荐
- 线性表的链式表示与实现
- C语言 队列的链式结构的实现与表示 数据结构 队列的实现与表示
- 2.3、线性表的链式表示与实现
- 数据结构(C语言版)---第三章栈和队列 3.4.2 队列的链式表示和实现(循环队列)
- 数据结构(C语言版)---第三章栈和队列 3.4.2 队列的链式表示和实现(单链表)
- 一个链式堆栈模块的接口(和数组实现完全一样)
- 线性表的链式表示和实现
- 线性表的链式表示和实现
- 实验二 线性表的链式表示与实现
- 链队列——队列的链式表示与实现
- 线性表的链式表示与实现
- 数据结构—线性表的链式表示和实现
- 链式堆栈的实现 (带头节点的链式堆栈)
- 队列的链式表示和实现
- 线性表的链式表示与实现
- 线性表的链式表示与实现
- 表的链式表示与实现
- 链队列——队列的链式表示和实现
- C/C++ 堆栈、队列的链式实现
- 2.3线性表的链式表示和实现