Data structure stack

Posted by simon71 on Mon, 22 Jun 2020 05:13:22 +0200

catalog

Article catalog

Stack

First of all, we need to explain that the Stack discussed in this paper is a kind of data structure, not a spatial structure in user state virtual memory. As a data structure, the Stack is a special linear table, and its data members are also consistent with the linear table. The difference is that stacks are last in, first out, while linear tables allow data elements to be inserted and deleted anywhere. Therefore, Stack is also called LIFO linear table, or LIFO table for short.

One of the application scenarios of stack is to change the sequence of data elements. The idea is to stack data elements in sequence, but to stack data elements according to the expected time as required, so as to change their sequence.

In software design, there are many examples of using stack to transform data element sequence. For example, in compiling a software system, it is necessary to frequently convert the arithmetic expression in the form of infix expression to the arithmetic expression in the form of suffix expression. For example, any programming language supporting recursive algorithm is implemented by stack, which requires the recursive algorithm to be executed first.

The characteristics and structure of stack

One of the core features of the stack is obviously last in, first out. The structure of stack has the concepts of stack bottom (with elements) and stack top (without elements), and the stack in and out can only be completed at the top of stack.

Operation set of stack

  • Stack initiate: set the stack length and set the stack top to zero.
  • Stack not empty: if the stack is not empty, 1 is returned, otherwise 0 is returned.
  • Stack push: inserts data elements at the top of the stack.
  • Stack Pop: Pop (delete and return) the data element at the top of the stack.
  • Stack top: takes the current stack top data element (returned but not deleted).

Pseudo code example

Declaration stack structure

#define MAX_SIZE 50

typedef int elem_type;
 
typedef struct sq_stack_s {
    elem_type data[MAX_SIZE];        //Elements in continuous memory storage stack
    int top;            //The subscript of the stack top element in the data array
} sq_stack_t;

Define stack operation function

  • StaticInitiate (constructor): the stack length has been determined when defining the data element array. Here, you only need to initialize the top position of the stack.
void static_initiate(sq_stack_t *s)
{
    s->top=0;	// Initialize stack top subscript value
}
  • Stackenotempty: non empty returns 1, otherwise returns 0.
int stack_not_empty(sq_stack_t *s)
{
    return s->top <= 0? 0: 1
}
  • StackPush: push the parameters to the top of the stack. 1 returned successfully, otherwise 0.
int stack_push(sq_stack_t *s, data_type d)
{
    if(s->top >= MAX_SIZE) {
        printf("The stack is full and cannot be inserted!\n")
        return 0;
    } else {
        s->elem_type[s->top] = d;
        S->top++;
        return 1;
    }
}
  • StackPop: pop up the data element at the top of the stack, assign the parameter and delete it. 1 returned successfully, otherwise 0.
int stack_pop(sq_stack_t *s, data_type *d)
{
    if(s->top <= 0) {
        printf("The stack is empty. No data element is out of the stack!\n");
        return 0;
    } else {
        s->top--;
        d = s->elem_type[s->top];
        return 1;
    }
}
  • StackTop: the data element at the top of the stack is fetched and given with parameters. It is not deleted. 1 returned successfully, otherwise 0.
 int stack_top(sq_stack_t *s, DataType *d)
 {
      if(s->top <=0 ) {
         printf("Stack empty!\n");
         return 0;
      } else {
         d = s->elem_type[s->top - 1];
         return 1;
      }
  }
  • Destrory (destructor, if necessary): free the memory space of the requested stack.
void destory(sq_stack_t *s) {}

Application example

Bracket matching problem:

Suppose an arithmetic expression contains parentheses, square brackets and curly brackets, write a function to determine whether the brackets in the expression are correctly matched, and design a test main function.

Algorithm idea: to check whether the brackets are matched, you can set a stack. If you read a bracket, if it is left bracket, you can directly enter the stack. If you read right bracket, and it is the same type as the left bracket at the top of the current stack, it means that the brackets are matched, and the left bracket number at the top of the stack is out of the stack, otherwise they are not matched. If the input sequence has been read and there is still an open bracket waiting for pairing in the stack, the bracket is not paired.

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include "string.h"

#include "LinkStack.h"	// Including chain stack implementation file

typedef char DataType;

int Match(DataType e,DataType ch);	// A function that checks whether parentheses are paired

int main()
{
	LinkStack S;
	char *p;
	DataType e;
	DataType ch[60];
	
	InitStack(&S);	// Initialize chain stack
	printf("Please enter bracketed expression");
	gets(ch);
	p = ch;
	
	while(*p)
	{
		switch(*p)
		{
		case '(':
		case '[':
		case '{':
			PushStack(S, *p++);    // Left parenthesis in stack.
			break;
		case ')':
		case ']':
		case '}':
			if (StackEmpty(S))    // First determine whether there is a left bracket.
			{
				printf("Missing left parenthesis.\n");
				return 0;
			}
			else
			{
				GetTop(S, &e);
				if (Match(e, *p))       // When judging whether the brackets match
				{
					PopStack(S, &e);    // Parentheses stack if they match
				}
				else
				{
					printf("Left bracket mismatch\n");
					return 0;
				}
			}
		default:	// If it is another character, do not process, point to the next character directly
			p++;
		}
	}
	if (StackEmpty(S))
	{
		printf("parenthesis matching\n");
		return 1;
	}
	else
	{
		printf("right parenthesis missing\n");
		return 0;
	}
}

int Match(DataType e,DataType ch)
{
	if (e == '(' && ch == ')')
	{
		return 1;
	}
	else if (e == '[' && ch == ']')
	{
		return 1;
	}
	else if (e == '{' && ch == '}')
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

Reference documents

https://mp.weixin.qq.com/s/aYTXIkNqv5j0YhylCBUlsw

Topics: Programming