// 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;
// The successor of the underlying stack element is null.
P-> next = top;
// P-> next = S. Top;
// Change the stack top pointer
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
{< br> stacknode * P = S. top;
int COUNT = 0;
while (p)
{< br> count ++;
P = p-> next;
}< br> return count;
}
Bool linkstack: Pop (linkstack & S, elemtype & E)
{
If (! Isempty (s ))
{
Stacknode * P = S. Top;
// Move the stack top pointer down
S. Top = S. Top-> next;
E = p-> data;
// Destroy the pointer space on the top of the original Stack
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 <"this stack has no elements! "<Endl;
Else
{
// Elements in the output Stack from the bottom of the stack to the top of the stack:
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;
}
}
// Knapsack problems
# Include "linkstack. H"
# Include <iostream>
Using namespace STD;
// Use the stack structure to handle the Knapsack Problem
Int main ()
{
int W [6] = {,};
int T = 10;
int n = 6;
linkstack s;
S. initstack (s);
int K = 0;
DO
{
while (T> 0 & K
{< br> If (t-W [k]> = 0)
{< br> S. push (S, k);
T = T-W [k];
}< br> K ++;
}
If (t = 0)
{
Cout <"solutions to a group of backpacking problems output:" <Endl;
S. stackdisplay (s );
}
S. Pop (S, k );
T = T + W [k];
K ++;
} While (! S. isempty (s) | K! = N );
Return 0;
}