Data structure and algorithm_ 02 stack

stack 1. Array implementation of ...
1. Array implementation of stack
2. Linked list implementation of stack
3. Application of stack

stack

1. Array implementation of stack

public class StackByArray { /** * Using array to simulate stack and implement method */ private int[] stack; private int top; public StackByArray(int stackSize) { stack = new int[stackSize]; top = -1;//Build array } //Store the top data and update the contents of the stack public boolean push(int data){ if(top > stack.length){ System.out.println("The stack is full and data cannot be added~"); return false; }else { stack[++top] = data; return true; } } //Judge whether it is empty public boolean isEmpty(){ return top == -1; } //Pop data from stack public int pop(){ if(this.isEmpty()){ System.out.println("Stack empty, no content"); return -1; }else { return stack[top--]; } } }

2. Linked list implementation of stack

public class StackByLink { /** * Linked list implementation of stack * The length of the linked list can be changed at any time */ private Node front;//Pointer to the bottom of the stack private Node rear;//Pointer to the top of the stack //Determine whether the stack is empty public boolean isEmpty(){ return front == null; } //Add data at the top of the stack public void push(int data){ Node node = new Node(data); if (this.isEmpty()){ front = node; rear = node; }else { rear.next = node; rear = node; } } //Pop data from stack public int data(){ Node newNode; if(this.isEmpty()){ System.out.println("Stack empty, no content~"); return -1; } newNode = front; if(newNode == rear){ front = null; rear = null; System.out.println("Empty stack, no content~"); return -1; }else { while (newNode.next != rear){ newNode = newNode.next; } newNode.next = rear.next; rear = newNode; return rear.data; } } } class Node{ int data; Node next; public Node(int data) { this.data = data; } }

3. Application of stack

Hanoi Tower problem

Problem Description:

  • There are three wooden stakes. The first one has n plates. The bottom plate is the largest and the top plate is the smallest. The problem of Hanoi tower is to move all the plates from the first wooden pile to the second wooden pile.

Rules of the game:

  • Only one plate can be moved from the top at a time;
  • Any plate can be moved from any stake to another stake
  • Smaller diameter plates must always be placed on larger plates
/**Three wooden piles a, B and C respectively *Enter the number of plates *The output corresponds to which stake to operate on */ public class HanoiTest { /** * Hanoi Tower problem */ public static void main(String[] args) { int m; System.out.println("input the number of diskes:"); Scanner scanner = new Scanner(System.in); m = scanner.nextInt(); System.out.println("The step to move %d diskes is--->>>" + m); hanoi(m,'A','B','C'); } public static void hanoi(int n,char one,char two,char three) { if(n==1) { move(one,three); } else { hanoi(n-1,one,three,two); HanoiTest.move(one,three); hanoi(n-1,two,one,three); } } public static void move(char x,char y) { System.out.println(x + "-->" + y + "\t"); } }

Solution of arithmetic expression

The type of expression depends on the position of the operator in the expression. There are three types

  • Middle order method: < operand 1 > < operator > < operand 2 >
  • Preorder method: < operator > < operand 1 > < operand 2 >
  • Post order method: < operand 1 > < operand 2 > < operator >

1. Middle order evaluation

  • Create two stacks to store operators and operands respectively
  • When taking out the operator, the priority of the operator in the stack must be compared first. If the priority of the operator in the stack is higher, the value of the operator in the stack will be calculated
  • During calculation, one operator and two operands are taken out for calculation, and the operation result is directly saved back to the operand stack to become an independent operand
  • When the expression is processed, clear the operator stack step by step until the stack is empty
  • Fetching the value from the operand stack is the result of the evaluation
    2. Preorder evaluation
    The advantage of preorder method is that it does not need to consider the problem of brackets and priority
  • Remove element from stack
  • Take out the element from the stack, perform the operation when encountering the operator, and save the result back to the operand stack
  • Take the element from the stack,
  • Take out the element from the stack, perform the operation when encountering the operator, and save the result back to the operand stack
  • Completion: take out the last operator in the stack, take out two operands from the operand stack for operation, save the operation result back to the operand stack, and the last value taken is the operation result
    3. Post order evaluation
    The advantage of the post order method is that it has no priority. The post order expression can be calculated directly on the computer without putting all the data on the stack for operation, and the expression can be read directly by loop

Middle sequence method to front and back sequence method

1. Bracket method
Middle order to front order

  • Completely enclose the middle order expressions in order
  • Move all operations to replace all left parentheses, and take the nearest as the principle
  • Remove all left parentheses
    Middle order to rear order
  • Completely enclose the middle order expressions in order
  • Move all operations to replace all right parentheses, and take the nearest as the principle
  • Remove all right parentheses

2. Stack method
ICP input priority in ISP stack

Middle order to front order

  • Read each character of the middle order expression from right to left
  • If the input is an operand, it is output directly
  • ')' has the lowest priority inside the stack, but the highest priority outside the stack
  • If "(", the operator in the stack will pop up until it reaches ")"
  • If ISP > ICP, the operator in the stack will pop up, otherwise it will be added to the stack

Middle order to rear order

  • Read each character of the middle order expression from left to right
  • If the input is an operand, it is output directly
  • If ISP > = ICP, the operator in the stack will pop up, otherwise it will be added to the stack
  • '(' has the lowest priority inside the stack, but the highest priority outside the stack
  • If a ")" is encountered, the operator in the stack will pop up until it reaches "("

An algorithm for converting middle order to post order

class class{ static int MAX=50; static char[] infix_q = new char[MAX]; //Constructor CH04_07 () { int i=0; for (i=0; i<MAX; i++) infix_q[i]='\0'; } // Operator priority comparison. If the input operator is less than the operator in the stack, the return value is 1, otherwise it is 0 public static int compare(char stack_o, char infix_o){ // In the middle order representation queue and temporary stack, the priority weight of the operator's priority table is INDEX/2 char[] infix_priority = new char[9] ; char[] stack_priority = new char[8] ; int index_s=0, index_i=0; infix_priority[0]='q';infix_priority[1]=')'; infix_priority[2]='+';infix_priority[3]='-'; infix_priority[4]='*';infix_priority[5]='/'; infix_priority[6]='^';infix_priority[7]=' '; infix_priority[8]='('; stack_priority[0]='q';stack_priority[1]='('; stack_priority[2]='+';stack_priority[3]='-'; stack_priority[4]='*';stack_priority[5]='/'; stack_priority[6]='^';stack_priority[7]=' '; while (stack_priority[index_s] != stack_o) index_s++; while (infix_priority[index_i] != infix_o) index_i++; return ((int)(index_s/2) >= (int)(index_i/2) ? 1 : 0); } //An algorithm for converting middle order to post order public static void infix_to_postfix(){ new DataInputStream(System.in); int rear=0, top=0, flag=0,i=0; char[] stack_t = new char[MAX]; for (i=0; i<MAX; i++) stack_t[i]='\0'; while (infix_q[rear] !='\n') { System.out.flush(); try { infix_q[++rear] = (char)System.in.read(); } catch (IOException e) { System.out.println(e); } } infix_q[rear-1] = 'q'; // Add q to the queue as the end symbol System.out.print("\t Sequential representation : "); stack_t[top] = 'q'; // Add # as an end symbol to the stack for (flag = 0; flag <= rear; flag++) { switch (infix_q[flag]) { // If the input is), the in stack operator is output until the in stack is( case ')': while(stack_t[top]!='(') System.out.print(stack_t[top--]); top--; break; // If the input is q, the operator that has not been output in the stack will be output case 'q': while(stack_t[top]!='q') System.out.print(stack_t[top--]); break; // The input is an operator. If it is less than the operator indicated by TOP in the stack, the operator indicated by the stack will be output // If it is greater than or equal to the operator indicated by TOP in the stack, the input operator is put on the stack case '(': case '^': case '*': case '/': case '+': case '-': while (compare(stack_t[top], infix_q[flag])==1) System.out.print(stack_t[top--]); stack_t[++top] = infix_q[flag]; break; // If the input is an operand, it is output directly default : System.out.print(infix_q[flag]); break; } } } //Main function test public static void main (String args[]){ new This category(); System.out.print("\t==========================================\n"); System.out.print("\t This program will convert it into a post order expression\n"); System.out.print("\t Please enter a middle order expression\n"); System.out.print("\t for example:(9+3)*8+7*6-12/4 \n"); System.out.print("\t The operators you can use include:^,*,+,-,/,(,)etc.\n"); System.out.print("\t==========================================\n"); System.out.print("\t Please enter the middle order expression: "); This category.infix_to_postfix(); System.out.print("\t==========================================\n"); }

11 September 2021, 19:28 | Views: 5364

Add new comment

For adding a comment, please log in
or create account

0 comments