数据结构基础系列——链栈的实现

来源:互联网 发布: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;}


完~

原创粉丝点击