Data structure stack

Posted by leoo24 on Thu, 02 Sep 2021 19:13:04 +0200

1. DS stack - output in reverse order (used by STL stack)

Title Description

C + + has its own stack object stack, so there is no need to write the specific implementation code of stack operation.

This topic mainly helps you to be familiar with the use of stack object, and then realize the reverse order output of string

Enter a string, press it into the stack according to the character input order, and then output it in reverse order according to the last in first out characteristics of the stack

Reference code used by the stack class

n include header file: #include

n create a stack object s (note that stack is a template class): stack s// The data type of the stack is character

n push a character ct onto the stack: s.push(ct);

n pop up the top element of the stack: s.pop();

n get the stack top element and put it into the variable c2: c2 =s.top();

n judge whether the stack is empty: s.empty(). If it is empty, the function returns true. If it is not empty, it returns false

input

Enter t in the first line, indicating that there are t test instances
From the second, enter a string for each line. Be careful that the string does not contain spaces

The following codes can be considered for string input:

#include

int main()

{ string str;

Int len;

cin>>str; // Save the input string in the variable str

len = str.length() / / get the length of the input string

}

output

Output each string in reverse order on each line

sample input

2
abcdef
aabbcc

sample output

fedcba
ccbbaa

Reference code

#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        string str;
        int len;
        cin>>str;
        len = str.size();
        stack<char> s;
        for(int i=0;i<len;i++)
        {
            char ct=str[i];
            s.push(ct);
        }
        for(int i=0;i<len;i++)
        {
            str[i]=s.top();
            s.pop();
        }
        cout<<str<<endl;


    }
}

2. DS stack - line editing

Title Description

Using the STL stack object of C + +, write a program to realize the line editing function. Line editing function: when entering # characters, backspace will be performed; If there is no character to return, no operation will be performed and no error will be reported

This program will not display # characters by default, so continuous input of multiple # characters means continuous execution of multiple backspace operations

For each line of characters entered, press enter to indicate the end of the string

Note: the stack implementation must be used, and the result must be positive order output

input

In the first line, enter an integer T, indicating that there are t lines of string to enter
Enter a string from the second line, a total of t lines

output

Each line outputs the final processed result. If there is no character output after processing, NULL will be directly output

sample input

4
chinaa#
sb#zb#u
##shen###zhen###
chi##a#####

sample output

china
szu
sz
NULL

Reference code

#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        string str;
        int len;
        cin>>str;
        len = str.size();
        stack<char> s;
        for(int i = 0;i<len;i++)
        {
            if(str[i] == '#')
            {
                if(!s.empty())
                    s.pop();
            }
            else
            {
                s.push(str[i]);
                //cout<<str[i];
            }
        }
        if(s.empty())
        {
            cout<<"NULL"<<endl;
            continue;
        }
        str.clear();
        len=0;
        while(!s.empty())
        {
            str+=s.top();
            len++;
            s.pop();
        }
        //cout<<len<<endl;
        for(int i=0;i<len;i++)
        {
            char ct=str[i];
            s.push(ct);
        }
        for(int i=0;i<len;i++)
        {
            str[i]=s.top();
            s.pop();
        }
        cout<<str<<endl;


    }
}

3. DS stack - bracket matching

Title Description

Bracket matching needs to be checked during expression processing. There are three types of bracket matching: "(" and ")", "[" and "]", "{" and "}". For example, the expression contains parentheses as follows:

()[()([])]{}
123456789101112

As can be seen from the above example, the 1st and 2nd parentheses match, the 3rd and 10th parentheses match, 4 and 5 match, 6 and 9 match, 7 and 8 match, and 11 and 12 match. It can be seen that the nesting of parentheses is complex. Using the stack can easily handle this parenthesis matching test. The following rules can be followed:

1. When the first left parenthesis is received, it indicates that a new set of matching checks begins; Then, if the left parenthesis is received continuously, it will continue to advance to the stack.

2. When the first right parenthesis is accepted, it matches the latest left parenthesis in the stack, indicating that a set of parentheses in the nest has been matched and eliminated

3. If the parentheses do not match exactly at the end, the input expression is wrong

It is recommended to use the stack object that comes with C + +

Reference code used by the stack class

n include header file: #include

n create a stack object s (note that stack is a template class): stack s// The data type of the stack is character

n push a character ct onto the stack: s.push(ct);

n pop up the top element of the stack: s.pop();

n get the stack top element and put it into the variable c2: c2 =s.top();

n judge whether the stack is empty: s.empty(). If it is empty, the function returns true. If it is not empty, it returns false

input

Enter a T in the first line, indicating that there will be t groups of test data below. Enter an expression in each line of the next t line. The expression only considers English half angle status input, and does not need to consider Chinese full angle input

output

For the expression of each line, check whether the parentheses match, enter ok if they match, and output error if they don't match

sample input

2
(a+b)[45+(-6)]
[58]/{(a+b)-6

sample output

ok
error

Reference code

#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        stack<char> s;
        string str;
        cin>>str;
        for(int i=0;i<str.size();i++)
        {
            if(str[i]=='('||str[i]=='{'||str[i]=='[')
                s.push(str[i]);
            else
            {
                if(str[i]==')')
                {
                    if(s.top()=='(')
                        s.pop();
                }
                else if(str[i]=='}')
                {
                    if(s.top()=='{')
                        s.pop();
                }
                else if(str[i]==']')
                {
                    if(s.top()=='[')
                        s.pop();
                }
            }

        }
        if(s.empty())
            cout<<"ok"<<endl;
        else
            cout<<"error"<<endl;
    }
}

4. DS stack - maze solving

Title Description

Give a schematic diagram of N*N maze matrix, start from the starting point [0,0], find the path to the end point [N-1, N-1]

Stack objects are required to be used for implementation. Refer to page 51 in section 3.2.4 of the textbook for specific algorithms

input

Enter t in the first line to indicate that there are t mazes

Input n in the second row, indicating that the first maze has n rows and N columns

From the third line, enter the status of each square in each line of the maze. 0 means that it can pass and 1 means that it cannot pass

Enter n lines

And so on, enter the next maze

output

Output maze paths one by one

If there is no path in the maze, output no path and enter

If there is a path in the maze, the x and y coordinates of each square in the path are output. From the starting point to the END point, every four squares are output to wrap the line, and finally END with the word END. Refer to the demonstration data for the specific format

The output code reference is as follows:

//path is a stack that stores paths. Each element in the stack contains x and y coordinates, which are represented by attributes xp and yp

//Path1 is a temporary stack that outputs the data of path in reverse order to path1, so that the path is output in positive order

if (!path.empty()) / / find the path

{/ /... Several codes to realize the data import of path path1

i=0; // The following is the code for the output path

while (!path1.empty())

{cpos = path1.top();

if ( (++i)%4 == 0 )

cout<<'['<<cpos.xp<<','<<cpos.yp<<']'<<"–"<<endl;

else

cout<<'['<<cpos.xp<<','<<cpos.yp<<']'<<"–";

path1.pop();

}

cout<<"END"<<endl;

}

else

cout<<“no path”<<endl; // Output no path not found

sample input

2
8
0 0 0 1 1 1 1 1
1 0 0 0 1 0 0 1
1 0 0 0 1 0 0 0
1 1 0 0 0 0 0 1
0 0 1 1 0 1 1 0
0 0 0 0 0 0 1 1
1 1 1 1 1 0 0 1
0 0 0 0 1 0 0 0
7
0 0 0 1 1 1 1
1 0 0 1 0 0 1
1 0 0 1 0 0 0
1 1 0 0 0 0 1
0 0 1 1 0 1 0
1 0 0 0 0 1 0
0 0 0 0 1 1 0

sample output

[0,0]–[0,1]–[0,2]–[1,2]–
[1,3]–[2,3]–[3,3]–[3,4]–
[4,4]–[5,4]–[5,5]–[6,5]–
[6,6]–[7,6]–[7,7]–END
no path

Reference code

#include<iostream>
#include<stack>
#include<string>
using namespace std;
class pos
{
public:
    int xp,yp;
    int p;
    int dir;
    void set(int a,int b,int c)
    {
        xp=a,yp=b,p=c;
    }
};

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        stack<pos> s;
        pos a[n+2][n+2];
        pos b,temp;
        for(int i=0;i<n+2;i++)
            for(int j=0;j<n+2;j++)
                a[i][j].set(i,j,1);
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
            {
                int k;
                cin>>k;
                a[i][j].set(i,j,k);
            }
        s.push(a[1][1]);
        int x=1,y=1;
        while(!s.empty())
        {
            b=s.top();
            s.pop();
            if(s.empty())
                temp=b;
            else
                temp=s.top();
            s.push(b);
            if(x==n&&y==n)
            {
                break;
            }
            if(a[x+1][y].p==0&&x+1!=temp.xp)
            {
                x++;
                a[x][y].p=1;
                s.push(a[x][y]);
            }
            else if(a[x][y+1].p==0&&y+1!=temp.yp)
            {
                y++;
                a[x][y].p=1;
                s.push(a[x][y]);
            }
            else if(a[x-1][y].p==0&&x-1!=temp.xp)
            {
                x--;
                a[x][y].p=1;
                s.push(a[x][y]);
            }
            else if(a[x][y-1].p==0&&y-1!=temp.yp)
            {
                y--;
                a[x][y].p=1;
                s.push(a[x][y]);

            }
            else
            {
                a[x][y].p=1;
                s.pop();
            }

        }
        if(!s.empty())
        {
            stack<pos> ans;
            while(!s.empty())
            {
                ans.push(s.top());
                s.pop();
            }
            int ii=0;
            while(!ans.empty())
            {
                temp=ans.top();
                cout<<'['<<temp.xp-1<<','<<temp.yp-1<<']'<<"--";
                if((++ii)%4==0)
                    cout<<endl;
                ans.pop();
            }
            cout<<"END"<<endl;
        }
        else
        {
            cout<<"no path"<<endl;
        }
    }
}

5. DS stack - expression evaluation

Title Description

Evaluates the result of an expression

It is implemented by using the stack object of C + +

Refer to the algorithm pseudo code P53-54 in the textbook

for example

  1. Push (OPTR, ‘#’); It means that the character # is pushed into the stack OPTR and converted into c + + code, which is OPTR.push('#');

  2. Pop(OPND, a); Represents the top element of pop-up stack opnd, and puts the top element into variable a. Therefore, changing to c + + code is two operations:
    a = OPND.top();
    OPND.pop();

  3. a = GetTop(OPND) means to obtain the stack top element of stack OPND and convert it into c + + Code: a = OPND.top();



input

The first input t indicates that there are t instances

From the second line, enter an expression in each line, and the end of each expression is marked with # indicating the end

Enter t line

output

Each line outputs the calculation result of an expression, which is expressed in the format of floating-point number (including 4 decimal places)

To control the decimal places of floating-point number output with cout, you need to add a library file and use fixed and setprecision functions. The code is as follows:

#include
#include
using namespace std;

int main()

{ double temp = 12.34

cout<<fixed<<setprecision(4)<<temp<<endl;

}

The output is 12.3400

sample input

2
1+2*3-4/5#
(66+(((11+22)*2-33)/3+6)*2)-45.6789#

sample output

6.2000
54.3211

Reference code

#include <iostream>
#include <stack>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <cstring>
using namespace std;
#define ok 0
#define error -1
#define overflow -1
#define opsetsize 7
typedef int Status;
char Prior[7][7] = {
	'>',
	'>',
	'<',
	'<',
	'<',
	'>',
	'>',
	'>',
	'>',
	'<',
	'<',
	'<',
	'>',
	'>',
	'>',
	'>',
	'>',
	'>',
	'<',
	'>',
	'>',
	'>',
	'>',
	'>',
	'>',
	'<',
	'>',
	'>',
	'<',
	'<',
	'<',
	'<',
	'<',
	'=',
	' ',
	'>',
	'>',
	'>',
	'>',
	' ',
	'>',
	'>',
	'<',
	'<',
	'<',
	'<',
	'<',
	' ',
	'=',
};
float Operate(float a, unsigned char theta, float b)
{
	if (theta == '+')
		return a + b;
	else if (theta == '-')
		return a - b;
	else if (theta == '*')
		return a * b;
	else if (theta == '/')
		return a / b;
}
char OPSET[opsetsize] = {'+', '-', '*', '/', '(', ')', '#'};
Status In(char Test, char *TestOp)
{
	for (int i = 0; i < opsetsize; i++)
	{
		if (Test == TestOp[i])
			return 1;
	}
	return ok;
}
char precede(char Aop, char Bop)
{
	int i, j;
	for (i = 0; i < opsetsize; i++)
	{
		if (OPSET[i] == Aop)
			break;
	}
	for (j = 0; j < opsetsize; j++)
	{
		if (OPSET[j] == Bop)
			break;
	}
	return Prior[i][j];
}
float EvaluateExpression(string MyExp)
{
	stack<char> OPTR;
	stack<double> OPND;
	char TempData[20];
	double Data, a, b, r;
	char theta, Dr[2];
	char c;
	int i = 0;
	OPTR.push('#');
	c = MyExp[0];
	strcpy(TempData, "\0");
	while (c != '#' || OPTR.top() != '#')
	{
		if (!In(c, OPSET))
		{
			Dr[0] = c;
			Dr[1] = '\0';
			strcat(TempData, Dr);
			c = MyExp[++i];
			if (In(c, OPSET))
			{
				Data = (float)atof(TempData);
				OPND.push(Data);
				strcpy(TempData, "\0");
			}
		}
		else
		{
			switch (precede(OPTR.top(), c))
			{
			case '<':
				OPTR.push(c);
				c = MyExp[++i];
				break;
			case '=':
				OPTR.pop();
				c = MyExp[++i];
				break;
			case '>':
				double a = OPND.top();
				OPND.pop();
				double b = OPND.top();
				OPND.pop();
				theta = OPTR.top();
				OPTR.pop();
				OPND.push(Operate(b, theta, a));
				break;
			}
		}
	}
	return OPND.top();
}
int main()
{
	string Exp;
	int t;
	double result;
	cin >> t;
	while (t--)
	{
		cin >> Exp;
		result = EvaluateExpression(Exp);
		cout << fixed << setprecision(4) << result << endl;
	}
	return 0;
}

Topics: C++ Algorithm data structure