栈的链式存储,即链式栈。它相比于顺序栈,
优点:
#include<iostream> using namespace std; typedef int ElemType; typedef struct stacknode //栈节点类型 { ElemType data; //值域 struct stacknode *next; //链域 }StackNode; class LinkStack //链式堆栈 { private: StackNode *stop; //栈顶指针 int num; //栈中节点个数 public: LinkStack(); //默认构造函数 LinkStack(const LinkStack &stack); //拷贝构造函数 ~LinkStack(); //析构函数 int size(); //获取栈节点个数 bool empty(); //判断栈是否为空 StackNode* top(); //获取栈顶元素 void pop(); //出栈 void push(ElemType data); //入栈 void clear(); //栈清空 void stackTraverse(void(*)(StackNode *)); //遍历栈 }; //类实现 LinkStack::LinkStack() //构建空栈 { stop=NULL; num=0; } LinkStack::LinkStack(const LinkStack &stack) //拷贝构造函数 { if(stop) //如果不为空,应该清除节点,释放内存 clear(); if(stack.stop) { StackNode *pnode,*p=stack.stop; stop=pnode=new StackNode; pnode->data=p->data; p=p->next; while(p) { pnode->next=new StackNode; pnode=pnode->next; pnode->data=p->data; p=p->next; } pnode->next=NULL; num=stack.num; } else LinkStack(); } LinkStack::~LinkStack() //析构函数 { StackNode *p,*q; p=stop; while(p) { q=p->next; delete p; p=q; } } int LinkStack::size() //获取栈大小 { return num; } bool LinkStack::empty() { return num==0; //判断栈是否为空 } StackNode* LinkStack::top() //获取栈顶元素 { if(stop) return stop; else return NULL; } void LinkStack::pop() //出栈 { if(stop) { StackNode *p=stop; stop=stop->next; delete p; num--; } } void LinkStack::push(ElemType data) //入栈 { StackNode *p=new StackNode; p->data=data; p->next=stop; stop=p; num++; } void LinkStack::clear() //栈清空 { num=0; StackNode *p,*q; p=stop; while(p) { q=p->next; delete p; p=q; } stop=NULL; } void LinkStack::stackTraverse(void(*visit)(StackNode *)) //遍历栈 { StackNode *p=stop; while(p) { visit(p); p=p->next; } printf("\n"); } void visit(StackNode *node) { printf("%-4d",node->data); }
int main() { cout<<"栈的实现:链式栈"<<endl; LinkStack stack; int data; cout<<"入栈,输入0结束!"<<endl; while(cin>>data && data) stack.push(data); printf("遍历栈\n"); stack.stackTraverse(visit); StackNode *pnode=stack.top(); printf("获取栈顶 %-4d\n",pnode->data); stack.pop(); printf("出栈,遍历栈\n"); stack.stackTraverse(visit); //使用拷贝构造函数 LinkStack s; s=stack; printf("测试拷贝构造函数\n"); printf("遍历栈\n"); s.stackTraverse(visit); printf("栈中元素个数是 %d\n",s.size()); stack.clear(); printf("栈清空后,栈是否为空?\n"); stack.empty()?printf("Yes!\n"):printf("No!\n"); system("pause"); return 0; }
原文地址:http://blog.csdn.net/zhangxiangdavaid/article/details/28679027