Stacks are widely used and often occur in a program where multiple stacks are used simultaneously. If the use of sequential stacks, because of the size of the stack space is difficult to accurately estimate, resulting in some stack overflow, some stack space is also very idle situation. In order to solve this problem, multiple stacks can share a large enough array space, by leveraging the dynamic characteristics of the stack to complement each other's storage space, which is the multi-stack sharing technology.
In the sequential stack sharing technology, the most common is two stacks of sharing technology, that is, double-ended stack. It mainly utilizes the stack bottom position unchanged, and the stack top position dynamic change characteristics.
The implementation code is as follows:
#include <iostream>
using namespace Std;
#define TRUE 1
#define FALSE 0
#define M 100
The storage structure of a double-ended sequential stack
typedef struct
{
int Stack[m];//stack[m] is the stack area
int top[2];//top[0] and top[1] are two top-of-stack indicators respectively
}dqstack;
Initializing a double-ended sequential stack
void Initstack (Dqstack *s)
{
S->top[0] =-1;
S->TOP[1] = M;
}
Double-ended sequential stack-in-stack operation
int Push (dqstack *s,int x,int i)//press the data element x into the I stack
{
if (s->top[0]+1 = = s->top[1])//Stack full
{
return FALSE;
}
Switch (i)
{
Case 0://No. No. 0 Stack
s->top[0]++;
S->stack[s->top[0]] = x;
Break
Case 1://No. 1th Stack
s->top[1]--;
S->STACK[S->TOP[1]] = x;
Break
Default://Parameter Error
return FALSE;
Break
}
return TRUE;
}
Double-ended sequential stack-out operation
int Pop (dqstack *s, int *x, int i)//eject the top element of the stack from the I stack and send it to X
{
Switch (i)
{
Case 0://# NO. 0 Stack out
if (S->top[0] ==-1)
{
return FALSE;
}
*x=s->stack[s->top[0]];
s->top[0]--;
Break
Case 1://# 1th stack out
if (s->top[1] = = M)
{
return FALSE;
}
*x = s->stack[s->top[1]];
s->top[1]++;
Break
Default
return FALSE;
Break
}
return TRUE;
}
This article is from the "Rock Owl" blog, please be sure to keep this source http://yaoyaolx.blog.51cto.com/10732111/1771293
Multi-stack sharing technology, initialization, stack-up, and stack operation of dual-end stacks