心之镇

~宁以致远~
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

链栈代码实现及背包问题解决

Posted on 2009-03-22 11:20  心之镇  阅读(564)  评论(0)    收藏  举报

//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;


}