[Algorithm design question] Dual stack structure

dual stack structure

Require

It is required to write dual-stack initialization, judge stack empty, stack full, push and pop.
Known dual-stack structure:

typedef struct
{
    
    
	int top[2], bot[2]; //栈顶和栈底指针
	SElemType *V;		//栈数组
	int m;				//栈最大可容纳元素
} DblStack;

algorithm thinking

  1. The two stacks share the vector space, and the bottom of the stack is set at the left and right ends. Initially, the bottom of the left stack is equal to the top of the stack and is equal to -1; the bottom of the right stack is equal to the top of the stack and is equal to m;
  2. When the tops of the two stacks are adjacent to each other, the stack is full (top of the right stack - top of the left stack = 1)
  3. The tops of the two stacks grow towards each other, and the pointer on the top of the stack points to the top element of the stack.
  4. When the left stack performs a push operation, the top element of the stack (shift to the right) + 1; when the stack is popped, the top element (shift to the left) - 1;
  5. When the right stack performs a push operation, the top element of the stack (shift left) - 1; when popping the stack, the top element (shift right) + 1;

Algorithm implementation

  1. Initialize dual stack
    Status InitStack(DblStack &S, int m){
          
          
    	S.V = new SElemType[m];//初始化数组空间
    	if(!S.V) return Error;
    	S.bot[0] = -1;//左栈的栈底指针
    	S.top[0] = -1;//左栈的栈顶指针
    	S.bot[1] = m;//右栈的栈底指针
    	S.top[1] = m;//右栈的栈顶指针
    	return OK;
    }
    
  2. Judging that the stack is empty
    int IsEmpty(DblStack S){
          
          
    	return S.top[i] == S.bot[i];
    }
    
  3. Judging that the stack is full
    int IsFull(DblStack S)	{
          
          
    	if (S.top[1] - top[0] == 1) return 1;
    	else return 0;
    }
    
  4. Specifies the stack insertion element
    Status DblPush(DblStack S, int i, SElemType x)	{
          
          
    	//判断栈满
    	if (S.top[1] - top[0] == 1) return ERROR;
    	if (i == 0) S.V[++S.top[0]] = x;
    	else S.V[--S.top[1]] = x;
    	return OK;
    }
    
  5. Specifies the stack to delete elements
    Status DblPop(DblStack &S, int i, SElemType &x)	{
          
          
    	//判断栈空
    	if (S.top[i] == S.bot[i]) return ERROR;
    	if (i == 0) x = S.V[S.top[0]--];
    	else x = S.V[S.top[1]++];
    	return OK;
    }
    

Guess you like

Origin blog.csdn.net/qq_43216714/article/details/123780833