数据结构基础系列——链栈的实现
来源:互联网 发布:ubuntu kylin 编辑:程序博客网 时间:2024/05/01 19:20
栈的操作只通过栈顶进行,不能越过栈顶向栈内取数据
#ifndef LinkStack_H#define LinkStack_Htemplate <class T>struct Node{T data;Node<T>* next;};template <class T>class LinkStack{public:LinkStack(){top = NULL;}~LinkStack();void Push(T x);//入栈T Pop();//出栈T GetTop()//取栈顶元素值{ if(top != NULL)return top->data;else return -1;}int Empty()//判断是否为空{if(!top)return -1;else return 1;}private:Node<T>* top;};template <class T>T LinkStack<T>::Pop(){if(!top)throw"下溢!";T j = top->data;Node<T>* p = top;top = top->next;//栈顶下移delete p;return j;}template <class T>void LinkStack<T>::Push(T x){Node<T>* s = new Node<T>;s->data = x;s->next = top;top = s;}//思路错误!对栈的构造认识不够,不像单链表那样需要头结点/*template <class T>LinkStack<T>::LinkStack(T a[],int n){top = new Node<T>;top->next = NULL;for(int i = 0;i<n;i++){Node<T>* s = new Node<T>;s->data = a[i];s->next = top;top = s;}}*/template <class T>LinkStack<T>::~LinkStack(){Node<T> *q;while(top){q = top;top = q->next;delete q;q = NULL;}}#endif
.cpp验证代码
#include "stdafx.h"#include "LinkStack.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){int r[] = {100,80,60,40,20};LinkStack<int> a;int j = sizeof(r)/sizeof(int);for(int i = 0;i<j;i++){a.Push(r[i]);}cout<<a.GetTop()<<endl;for(int i = 0;i<j;i++){try{cout<<a.Pop()<<endl;}catch(char* s){cout<<s<<endl;}}cout<<a.Empty()<<endl;try{cout<<a.Pop()<<endl;}catch(char* s){cout<<s<<endl;}a.Push(326);cout<<a.Empty()<<endl;cout<<a.GetTop()<<endl;return 0;}
完~
- 数据结构基础系列——链栈的实现
- 数据结构基础系列——单链表的实现
- 数据结构基础——栈的C++实现
- 数据结构C语言实现系列[2]——栈
- 数据结构C语言实现系列[2]——栈
- 数据结构C语言实现系列——双向链表
- 数据结构C语言实现系列[3]——关于栈的一些习题
- 基础数据结构--栈实现
- 数据结构基础6_链栈的实现
- 数据结构基础——循环队列的C++实现
- 数据结构基础(一)栈的实现
- 数据结构基础【06】栈的链式实现
- 基础数据结构--双向链表的实现
- 数据结构——用数组实现的栈的基础功能
- 基础数据结构:栈、队列——Python实现
- 数据结构基础java实现—双向链表
- 重学数据结构系列之——线性表基础
- 重学数据结构系列之——二叉树基础
- made in?
- MySQL 数据库性能优化之索引优化
- 灯
- 这几天qc开会
- MySQL 数据库性能优化之SQL优化
- 数据结构基础系列——链栈的实现
- 关于java的序列化
- 秒杀多线程第二篇 多线程第一次亲密接触 CreateThread与_beginthreadex本质区别
- 网页制作常用代码
- Python_使用ElementTree解析xml文件
- UIViewContentMode各类型效果
- MySQL数据库性能优化之存储引擎选择
- svn
- 模态窗口和非模态窗口的区别