Java implementation stack detailed and instance code _java

Source: Internet
Author: User

A stack is a list that restricts insertion and deletion to only one position, the end of the list, called the top of the stack, and the push and pop for the basic operation of the stack, which is the insert, the latter is deleted.

Stacks are also FIFO tables.

There are two ways to implement a stack, one is to use an array, and one is to use a linked list.

public class Myarraystack<e> {

 private arraylist<e> list = new arraylist<> ();

 public void push (E e) {
 list.add (e);
 }

 Public E POPs () {return
 List.remove (List.size ()-1);
 }

 Public E Peek () {return
 List.get (List.size ()-1);
 }

 public Boolean IsEmpty () {return
 list.size () = 0;
 }
}

public class Mylinkstack<e> {

 linkedlist<e> list = new linkedlist<> ();

 public void push (E e) {
 list.addlast (e);
 }

 Public E-Pop () {return
 list.removelast ();
 }

 Public E-Peek () {return
 list.getlast ();
 }

 public Boolean IsEmpty () {return
 list.size () = 0;
 }
}

Application of Stack

Balance symbol

Given a string of code, we check that the parentheses in this code are grammatically compliant.

For example: [{()}] This is legal, but [{]} () is illegal.

The following is the test code:

public class Balancesymbol {public boolean isbalance (string string) {myarraystack&lt;character&gt; stack = new Myarr
 Aystack&lt;&gt; ();
 char[] array = String.tochararray ();
  for (char Ch:array) {if (' {[] indexOf (CH) &gt;= 0) {stack.push (CH);
  else if ("}]". INDEXOF (CH) &gt;= 0) {if (Ismatching (Stack.peek (), ch)) {stack.pop ();
 }} return Stack.isempty (); Private Boolean ismatching (char Peek, char ch) {if (peek = = ' {' &amp;&amp; ch = = '} ') | | (Peek = = ' [' &amp;&amp; ch =] ') | | (Peek = = ' (' &amp;&amp; ch = = ')]
 {return true;
 return false;
 public static void Main (string[] args) {Balancesymbol symbol = new Balancesymbol ();
 String string = "public static void Main (string[] args) {Balancesymbol symbol = new Balancesymbol ();}";
 String string2 = "public static void Main (string[] args) {Balancesymbol symbol = new Balancesymbol ([);}]";
 System.out.println (Symbol.isbalance (string));
 System.out.println (Symbol.isbalance (string2));
}
}
 

Suffix expression

For example, one of the following input, to calculate the corresponding results,

3 + 2 + 3 * 2 =?

This is different in the order of calculation, if the result is 16 from left to right, if the result is 11 according to the mathematical priority.

If you convert the infix expression above to the suffix expression:

3 2 + 3 2 * +

If you use a suffix expression to calculate the value of this expression, it will be very simple, just use one stack.

Whenever you encounter a number, put the number into the stack.

Every time an operator is encountered, a pop-up 2 elements are calculated based on the operator, into the stack.

The only element of the final pop-up stack is the result of the calculation.

/**
 * Simplified version, one digit per operand, and assumes string legal/public
class Postfixexpression {public

 static int calculate (string String) {
 myarraystack<string> stack = new myarraystack<> ();

 char[] arr = String.tochararray ();

 for (char Ch:arr) {
  if ("0123456789". IndexOf (CH) >= 0) {
  stack.push (ch + "");
  } else if ("+-*/". IndexOf (CH) >= 0) {
  int a = Integer.parseint (Stack.pop ());
  int b = Integer.parseint (Stack.pop ());
  if (ch = = ' + ') {
   Stack.push ((A + B) + "");
  } else if (ch = =-') {
   Stack.push ((a-b) + "");
  } else if (ch = = ' * ') {
   Stack.push ((A * b) + "");
  } else if (ch = = '/') {Stack.push (a
   /b) + "");
 }} Return Integer.parseint (Stack.peek ());
 }

 public static void Main (string[] args) {
 System.out.println (Calculate ("32+32*+"));
 }


infix expression converted to suffix expression

Suppose you only run +,-,*,/, () these expressions. And the expression is valid.

A + b * C-(d * e + F)/G after the converted suffix expression is as follows:

A b c * + D e * f + g/-

Use the stack infix suffix steps as follows:

    1. When you read the operand and immediately output it
    2. If you encounter an operator in the stack, if the opening parenthesis you encounter is also placed in the stack
    3. If the closing parenthesis is encountered, the stack element starts to pop up until the corresponding opening parenthesis is encountered, and the opening parenthesis only pops up and does not output.
    4. If other symbols are encountered, the pop-up stack element from the stack knows that a lower priority element is found.
Import Java.util.HashMap;

Import Java.util.Map; public class Expressionswitch {private static map&lt;character, integer&gt; Map = new Hashmap&lt;character, integer&gt;

 ();
 static {map.put (' + ', 0);
 Map.put ('-', 1);
 Map.put (' * ', 2);
 Map.put ('/', 3);
 Map.put (' (', 4); } private static char[][] Priority = {//current operator//+-*///* stack + */{' &gt; ', ' &gt; ', ' &lt; ', ' &lt; ', ' & lt; '},/* top-*/{' &gt; ', ' &gt; ', ' &lt; ', ' &lt; ', ' &lt; '},/* * * */{' &gt; ', ' &gt; ', ' &gt; ', ' &gt; ', ' &lt; '},/*

 /*/{' &gt; ', ' &gt; ', ' &gt; ', ' &gt; ', ' &lt; '},/* characters (*/{' &lt; ', ' &lt; ', ' &lt; ', ' &lt; ', ' &lt; '},};

 public static string Switch1 (String string) {StringBuilder builder = new StringBuilder ();

 char[] arr = String.tochararray ();
 myarraystack&lt;character&gt; stack = new myarraystack&lt;&gt; ();
  for (char Ch:arr) {if ("0123456789abcdefghijklmnopqrstuvwxyz". IndexOf (CH) &gt;= 0) {builder.append (CH);
  Or else if (' (' = = ch ') {stack.push (CH); else if ('= = = ch) {while (True &amp;&amp;!stack.isempty ()) {char tmp = Stack.pop ();
   if (tmp = = ' (') {break;
   else {builder.append (TMP);
   }} else {while (true) {if (Stack.isempty ()) {Stack.push (CH);
   Break
   char tmp = Stack.peek ();
   if (Ispriorityhigh (TMP, CH)) {Builder.append (Stack.pop ());
   else {stack.push (ch);
   Break
 }}} while (!stack.isempty ()) {Builder.append (Stack.pop ());
 return builder.tostring ();
 private static Boolean Ispriorityhigh (char tmp, char ch) {return priority[map.get (tmp)][map.get (ch)] = = ' &gt; ';
 public static void Main (string[] args) {System.out.println (Switch1 ("a+b*c-(d*e+f)/g"));
 

 }
}

Through this article, I hope you have the knowledge of Java stack, thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.