您的位置:首页 > 其它

堆栈的链表实现

2013-12-11 10:01 155 查看


 

#include <iostream>

#include <iomanip>

using namespace std;

 

typedef class List

{

public:

 int data;

 class List* next;

}Node,*Link;

 

//指向堆栈顶端的指针

Link top=NULL;

 

//判断是否为空堆栈

bool IsEmpty()

{

 if(NULL==top)

  return true;

 return false;

}

 

void push(int data)

{

 Link AddNode=new Node; //新加入结点的指针

 AddNode->data=data;  

 AddNode->next=top;  //将新结点指向堆栈的顶端

 top=AddNode;   //新结点成为堆栈的顶端

}

 

int pop()

{

 if(IsEmpty())

 {

  cout<<"目前为空堆栈"<<endl;

  return -1;

 }

 

 Link Pointer=top;  //指向堆栈的顶端

 top=top->next;   //将堆栈顶端的指针指向下一个结点

 int tmp=Pointer->data; //取出堆栈数据

 delete Pointer;   //将结点占用的内存空间释放

 return tmp;

}

 

int main()

{

 int value;

 cout<<" 堆栈的链表实现\n\n";

 cout<<" 请输入5个数字:";

 for(int i=0;i<5;i++)

 {

  cin>>value;

  push(value);

 }

 

 cout<<"\n 从堆栈取出数据:";

 cout<<"\n===================\n";

 while(!IsEmpty())

 {

  cout<<" 堆栈弹出的数据为:"<<setw(2)<<pop()<<endl;

 }

 cout<<"\n\n";

 return 0;

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: