//StackNode.h
#ifndef _STACKNODE
#define _STACKNODE
/*StackNode.h*/
#include <iostream>
using namespace std;
typedef int ElemType;
class StackNode
{
public:
ElemType data;
StackNode *next;
StackNode():data(NULL),next(NULL) { }
~StackNode(){ }
};
#endif
//LinkStack.h
#ifndef _LINKSTACK
#define _LINKSTACK
#include "StackNode.h"
class LinkStack
{
private:
StackNode *top;
public:
LinkStack(){}
~LinkStack(){}
void InitStack(LinkStack &);
bool IsEmpty(LinkStack);
int StackLength(LinkStack)const;
void Push(LinkStack &,ElemType);
bool Pop(LinkStack &,ElemType &);
void GetTop(LinkStack,ElemType &);
void StackDisplay(LinkStack);
};
#endif
//LinkStack.cpp
#include "LinkStack.h"
void LinkStack::InitStack(LinkStack &S)
{
top=NULL;
// S.top=NULL;
}
void LinkStack::Push(LinkStack &S,ElemType e)
{
StackNode *p=new StackNode;
p->data=e;
//棧底元素的後繼為NULL
p->next=top;
//p->next=S.top;
//改變棧頂指標
top=p;
// S.top=p;
}
bool LinkStack::IsEmpty(LinkStack S)
{
if(this->top==NULL)
return true;
else
return false;
}
int LinkStack::StackLength(LinkStack S) const
{
StackNode *p=S.top;
int count=0;
while(p)
{
count++;
p=p->next;
}
return count;
}
bool LinkStack::Pop(LinkStack &S,ElemType &e)
{
if(!IsEmpty(S))
{
StackNode *p=S.top;
//棧頂指標下移
S.top=S.top->next;
e=p->data;
//銷毀原棧頂指標空間
delete p;
return true;
}
else
return false;
}
void LinkStack::GetTop(LinkStack S,ElemType &e)
{
StackNode *p=S.top;
e=p->data;
}
void LinkStack::StackDisplay(LinkStack S)
{
if(IsEmpty(S))
cout<<"該棧沒有元素!"<<endl;
else
{
//從棧底到棧頂輸出棧中的元素:
int n=S.StackLength(S);
ElemType *elem=new ElemType[n];
StackNode *p=S.top;
for (int i=0;i<n;i++)
{
elem[i]=p->data;
p=p->next;
}
for(int i=n-1;i>=0;i--)
cout<<elem[i]<<endl;
}
}
//背包問題
#include "LinkStack.h"
#include <iostream>
using namespace std;
//利用棧的結構來處理背包問題
int main()
{
int w[6]={1,8,4,3,5,2};
int T=10;
int n=6;
LinkStack S;
S.InitStack(S);
int k=0;
do
{
while(T>0&&k<n)
{
if(T-w[k]>=0)
{
S.Push(S,k);
T=T-w[k];
}
k++;
}
if(T==0)
{
cout<<"輸出一組背包問題的解:"<<endl;
S.StackDisplay(S);
}
S.Pop(S,k);
T=T+w[k];
k++;
}while(!S.IsEmpty(S)||k!=n);
return 0;
}