用链表实现栈C++实现源码
2013-04-19 16:21
197 查看
头文件:
源文件:
测试文件:
//Stack.h struct node; typedef struct node *Stack; Stack CreateStack(); void Push( int, Stack ); void PrintStack( Stack ); void Pop(Stack); int StackLength( Stack );
源文件:
//Stack.cpp #include "Stack.h" #include <iostream> using namespace std; struct node{ int data; node *next; }; Stack CreateStack() { Stack S; S = (node *)malloc(sizeof(node)); if( S == NULL ) cout<<"内存分配失败!"<<endl; S->next = NULL; return S; } void Push( int x, Stack S ) { node *tmp; tmp = (node *)malloc(sizeof(node)); if( tmp == NULL ) cout << "内存分配失败!"<<endl; else{ tmp->data = x; tmp->next = S->next; S->next = tmp; } } void Pop(Stack S) { node *top; if( S->next == NULL ) cout << "Pop失败:空栈!"<<endl; else{ top = S->next; S->next = S->next->next; free(top); } } int StackLength( Stack S) { int n = 0; while( S->next != NULL ) { S = S->next; n++; } return n; } void PrintStack(Stack S) { cout << "Stack: " << endl; S = S->next; //第一个S,S为空 while( S != NULL ) { //cout << "S!=NULL"<<endl; cout << S->data ; S = S->next; } cout << endl; }
测试文件:
//main.cpp #include "Stack.h" #include <iostream> using namespace std; void main() { int n; int x; Stack S = CreateStack(); cout << "输入n:"; cin >> n; while( n-- ) { cout <<" 输入数字:"; cin >> x; Push( x, S); } PrintStack(S); int m; cout << "输入Pop个数m:"; cin >> m; while(m--) { Pop(S); } PrintStack(S); cout << "栈的长度:" << StackLength(S) << endl; PrintStack(S); system("PAUSE"); }
相关文章推荐
- 二级指针实现单链表的插入、删除及 linux内核源码双向链表之奇技
- Java数据结构----栈(Stack)源码分析和用链表简单实现
- 数据结构---单链表实现(源码)
- java实现链表 源码
- 二级指针实现单链表的插入、删除及 linux内核源码双向链表之奇技
- 操作系统模拟内存管理实验,C语言链表实现,附源码
- linux 链表实现源码学习
- 结合redis设计与实现的redis源码学习-3-链表
- Redis 源码解析 string内部实现原理之链表
- [150420][C++]数据结构复习——链表实现源码
- C语言 链表的基本操作实现 源码
- 单链表 基本操作 的实现源码
- Android版数据结构与算法(三):基于链表的实现LinkedList源码彻底分析
- 实现半透明的popupwindow的源码
- 谁都能看懂的单点登录(SSO)实现方式(附源码)
- 单链表的实现(python)
- SwitchButton 开关按钮 的多种实现方式 (附源码DEMO)
- Java 数据结构链表操作实现代码
- C++实现循环双向链表
- TraceRoute(tracert)源码(基于ICMP.DLL实现)