vector〈int〉實現堆棧
這是一個用鏈表實現的堆棧,代碼實現如下:
- 頭文件stack.h
//:stacklink:stack.h
class Stack{
struct Link{
void* data;
Link* next;
Link(void* dat,Link *link);
~Link();
}* head;
public:
Stack();
~Stack();
void push(void* dat);
void* pop();
///:~
- 堆棧實現stacklib.cpp
//:stacklink:stacklib.cpp {O}
#include "stack.h"
#include <iostream>
//#include "require.h"
using namespace std;
Stack::Link::Link(void* dat,Link *link)
{
data=dat;
next=link;
}
Stack::Link::~Link(){}
Stack::Stack()
{
head=0;
}
void Stack::push(void* dat)
{
Link* newnode=new Link(dat,head);
head=newnode;
}
void* Stack::pop()
{
if(head==0)
return 0;
void* result=head->data;
Link* oldhead=head;
head=head->next;
delete oldhead;
return result;
}
Stack::~Stack()
{
//require(head==0,"Stack is not empty!")
//if(head==0)
// cout<<"Stack is not empty!"<<endl;
}
///:~
- 測試stacktest.cpp
//:stacklink:stacktext.cpp
#include <iostream>
#include <string>
#include "stack.h"
using namespace std;
class Simple{
private: int sim;
public:Simple(int m);
public:~Simple();
};
Simple::Simple(int m)
{
sim=m;
cout<<"Simple "<<sim<<endl;
}
Simple::~Simple()
{
cout<<"~Simple "<<sim<<endl;
}
int main()
{
string str[3]={"zhou","wen","xiang"};
for(int i=0;i<3;i++)
{
cout<<str[i]<<" ";
}
cout<<endl;
Stack Ss;
for (int i=0;i<3;i++)
{
Ss.push(new string(str[i]));
}
string* s;
while((s=(string*)Ss.pop())!=0)
{
cout<<*s<<" ";
delete s;
}
cout<<endl;
system("pause");
}
///:~
心得:
- struct 結構可以有構造函數與析構函數,如上面Link結構的構造函數Link()與析構函數~Link(),這裏的析構函數並沒有做清除處理,因爲如果在析構函數~link()中做清楚處理,satck::pop()無法得到結果,因爲該節點已經被刪除了。
- head是struct Link*類型的變量,可以初始化爲0,即head=0。