c++编写一个类,实现简单的栈(用链表结构)

来源:百度知道 编辑:UC知道 时间:2024/06/03 10:10:30
数据的操作按先进后出的顺序。

成员函数:
void stack::put(int item);//将数据item插入到栈中
int stack::get();//从栈中取一个数据

数据成员:
一个指向链首的指针

链表结构为:
struct Node{
int a;
Node* next;
};

使用对象的过程:
stack st;

st.put(10);
st.put(12);
st.put(14);

cout<<st.get()<<endl;//输出14,栈中剩下10,12
cout<<st.get()<<endl;//输出12,栈中剩下10

//stack.h
#include<iostream.h>

struct Node{
int a;
Node* next;
};

class Stack{
public:
Stack(){
head=NULL;
}
void put(int item);
int get();

protected:
Node* head;
};

//-----------------------------------------------------------
//stack.cpp
#include "stack.h"

void Stack::put(int item){
Node* ss=new Node;
ss->a=item;
if(head==NULL){
head=ss;
ss->next=NULL;
}
else{
Node* sEnd=head;
ss->next=sEnd;
head=ss;
}
}

int Stack::get(){
if(head==NULL){
cout<<"the end of stack.\n";
return 0;
}
else{
int aa=head->a;
Node* ss=head;
head=head->next;
delete ss;
return aa;
}
}

//-----------------------------------------------------
//main.cpp