The basic method of realizing stack data structure with Java code is summed up _java

Source: Internet
Author: User
Tags int size

Chained implementations:

Add and remove elements in the stack, maintain a node at the top of the stack and a count variable to indicate the size of the stack:
Private Linearnode top; Point to top of stack
private int count;//tag stack size
Every time the stack and stack in the list of the table header: (also can be the end of the table, the implementation of the same way)
Top---> element 1---> element 2---> Element 3 ...
Implementation (incidental test main):
Linkedstack

Package Stack;
Import Bag.linearnode; In order to focus on the implementation of the algorithm, the exception will be printed directly out of the program, and no longer declare the exception class public class Linkedstack implements Stackadt {private Linearnode top;
    vate int count;//tag stack size public static void main (string[] args) {Linkedstack stack = new Linkedstack ();
    System.out.println ("Press stack from 0 to 10");
    for (int i = 0;i < 10;i++) Stack.push (i);
    System.out.println ("Perform 5 consecutive stack operations");
    for (int i = 0;i < 5;i++) Stack.pop (); System.out.println ("Stack is empty?)
    : "+ stack.isempty ());
    System.out.println ("Stack size is:" + stack.size ());
    System.out.println ("Stack top element is:" + stack.top.getElement ());  
  System.out.println ("Stack top element is:" + stack.peek ());
    Public Linkedstack () {top = null;
  Count = 0;
  public int size () {return count;
  public Boolean IsEmpty () {return (size () = 0);
    public void push (Object element) {linearnode node = new Linearnode (element);
    Node.setnext (top);
    top = node;
  count++;
  Public Object pop () {  if (IsEmpty ()) {System.out.println ("stack is empty!");
    System.exit (1);
    Object result = Top.getelement ();
    top = Top.getnext ();
    count--;
  return result;
    public Object Peek () {Object result = Top.getelement ();
  return result;
 }
}

Run Result:
Press the stack 0 to 10 in turn
Perform 5 consecutive stack operations
Is the stack empty? : false
The size of the stack is: 5
Top element of Stack: 4
Top element of Stack: 4

Array implementation:

The bottom of the stack is always the position where the array is labeled 0, and the stack stack starts with the last element of the array subscript:

Private object[] contents;
The private int top;//top marks the next placement in the stack, and also represents the stack's capacity size, compared to the chained implementation count!!!

Implementation (incidental test main):
Arraystack

Package Stack;
  public class Arraystack implements Stackadt {private object[] contents;
  The private int top;//top marks the next placement in the stack, and also represents the stack's capacity size, compared to the chained implementation count!!!
  private static int SIZE = 10;
    Public Arraystack () {contents = new object[size];
  top = 0;
    public void expand () {//by applying for an auxiliary space, one object[per expansion capacity] Larger = new Object[size () *2];
    for (int index = 0;index < top;index++) Larger[index] = Contents[index];
  contents = larger;
  public int size () {return top;
  public Boolean IsEmpty () {return (size () = 0);
    public void push (Object element) {//if (IsEmpty ())//expand ();
    if (top = = contents.length) expand ();
    Contents[top] = element;
  top++;
      Public Object Pop () {if (IsEmpty ()) {System.out.println (' stack is empty! ');
    System.exit (1);
    Object result = Contents[top-1];
    Contents[top-1] = null;//out stack top--;  
    return result;
     * * The book is easy to write::: * top--; * OBJECT result = Contents[top];
    * Contents[top] = null;*/} public Object Peek () {object result;
    if (IsEmpty ()) result = NULL;
    else result = contents[top-1];
  return result;
    public static void Main (string[] args) {Arraystack stack = new Arraystack ();
    System.out.println ("will 0 to 24 sequentially press the stack, and then 10 times out of the stack");
    for (int i = 0;i < 25;i++) Stack.push (i);
    for (int i = 0;i < 10;i++) Stack.pop ();
    System.out.println ("Stack size is:" + stack.size ()); System.out.println ("Stack is empty?)
    : "+ stack.isempty ());
  System.out.println ("Stack top element is:" + stack.peek ());
 }
}

Run Result:
Press the stack 0 to 24 sequentially, then 10 times in a row
The size of the stack is: 15
Is the stack empty? : false
Top element of Stack: 14

Using collection LinkedList to simulate stacks
method
Java generics allow LinkedList to simulate stacks that store a variety of data types, including Int,double,string,object, and so on, introducing several API interfaces to use:

Into the stack

  void AddFirst (e e); Inserts the specified element at the beginning of this list 


Get top element of stack

  E GetFirst (); Returns the first element of this list 


Out Stack

  E Removefirst (); Remove and return the first element of this list 


Stack empty

  Boolean IsEmpty (); Judge Stack Empty 

Sample code

 Import java.util.LinkedList; 
  Import java.util.NoSuchElementException; 
   
   
  public class Simulatestack { 
    private linkedlist<integer> stack = new linkedlist<integer> (); 
     
    public Boolean IsEmpty () {return 
      this.stack.isEmpty (); 
    } 
     
    public void push (int data) { 
      this.stack.addFirst (data); 
    } 
     
    public int pops () throws nosuchelementexception{return 
      This.stack.removeFirst (); 
    } 
     
    public int GetTop () throws nosuchelementexception{return 
      This.stack.getFirst (); 
    } 
     
    public static void Main (String args[]) { 
      Simulatestack s = new Simulatestack (); 
       
      S.push (1); 
      S.push (2); 
      S.push (3); 
       
      while (! S.isempty ()) { 
        int data = S.gettop (); 
        SYSTEM.OUT.PRINTLN (data); 
        S.pop ();}} 
   

Related Article

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.