Java stack and queue __java data structures and algorithms

Source: Internet
Author: User
Java implementation stacks and queues

Stack: LIFO (backward first out)

Queues: FIFO (first-in first Out)

Sequential storage structure implementation of stacks:

/** * Based on array implementation of sequential stack * @param <E> * * public class Stack<e> {private object[] data = null;   private int maxsize=0;  stack capacity private int top =-1;   Stack top Pointer/** * constructor: Initialize stack/stack () {This (10) according to the given size;
            The default stack size is ten} stack (int initialsize) {if (initialsize >=0) {this.maxsize = InitialSize;
            data = new Object[initialsize];
        top =-1;
        }else{throw new RuntimeException ("initialization size cannot be less than 0:" + initialsize);
    }///Null public boolean empty () {return top==-1 true:false; }//Stack, first element top=0 public boolean push (E e) {if (top = maxSize-1) {throw new Runtimeexce Ption ("The stack is full, the element cannot be placed on the stack.")
        ");
            }else{data[++top]=e;
        return true; }//view top element of stack without removing public E peek () {if (top = 1) {throw new RuntimeException ("Stack is empty.")
        ");
            }else{Return (E) data[top]; }//pop-up stack top element public E pop () {if (+ = 1) {throw new RuntimeException ("Stack is empty.")
        ");
        }else{return (E) data[top--];
        }//Returns the position of the object on the stack, with 1 as the Cardinal public int search (e e) {int i=top;
            while (top!=-1) {if (Peek ()!= e) {top-;
            }else{break;
        int result = Top+1;
        top = i;      
    return result; }
}

The chain-type storage structure of the stack is implemented:

public class Linkstack<e> {//Chain stack node private class node<e>{E e;
        
        Node<e> Next;
            Public node () {} public node (e E, Node next) {this.e = E;
        This.next = Next;   } private node<e> top;  stack top element private int size;
    Current stack size public linkstack () {top = null;
    }//Current stack size public int length () {return size;
    }//Null public boolean empty () {return size==0;
        //To Stack: Let top point to the newly created element, and the next reference to the new element points to the original stack top element public boolean push (E e) {top = new Node (e,top);
        Size + +;
    return true; //view top of stack element but do not remove public node<e> peek () {if (empty ()) {throw new RuntimeException ("Empty stack exception 。
        ");
        }else{return top; }///out Stack public node<e> pop () {if (empty ()) {throw new RuntimeException ("Empty stack exception.")
        ");
     }else{       node<e> value = top; The top of the stack is obtained top.next;  Let the top reference point to the next element of the original stack value.next = null;
            Releases the next reference size of the original stack top element--;
        return value; }
    }
}

Stack structure based on LinkedList implementation:

Import java.util.LinkedList;

/**
 * Based on the LinkedList implementation stack
 * in the LinkedList power only select part of the implementation of the stack-based interface * * Public
class Stacklist<e> {
    Private linkedlist<e> LL = new linkedlist<e> ();
    
    into stack public
    void push (E e) {
        ll.addfirst (e);
    }
    
    View the top element of the stack without removing public
    E Peek () {return
        ll.getfirst ();
    }
    
    Out Stack public
    E POPs () {return
        ll.removefirst ();
    }
    
    Null-
    Empty public boolean () {return
        ll.isempty ();
    }
    
    Print stack element public
    String toString () {return
        ll.tostring ();
    }
}

Sequential storage structure implementation of queues

public class Queue<e> {private object[] data=null; private int maxSize;  Queue capacity private int front;   Queue headers, allowing the deletion of private int rear;
    End of queue, allow insert//constructor public queue () {this (10);
            The public Queue (int initialsize) {if (initialsize >=0) {this.maxsize = InitialSize;
            data = new Object[initialsize];
        Front = rear = 0;
        }else{throw new RuntimeException ("initialization size cannot be less than 0:" + initialsize);
    }///Null public boolean empty () {return rear==front?true:false; }//Insert public boolean Add (e e) {if (rear== maxSize) {throw new RuntimeException ("queue full, unable to insert The new element.
        ");
            }else{data[rear++]=e;
        return true; }//Returns the first element of the team, but does not delete public E peek () {if (empty ()) {throw new runtimeexception ("Null queue exception.")
        ");
        }else{return (E) Data[front];
    
    }    
    }Out Team Public E poll () {if (empty ()) {throw new runtimeexception ("Null queue exception.")
        ");  }else{e value = (e) Data[front];     The value of the element at the front end of the reserved queue data[front++] = null;
        Release the element return value of the front end of the queue;
    }//Queue Length public int length () {return rear-front; }
}

Sequential storage structure implementation of

loop queue

Import Java.util.Arrays;
    public class Loopqueue<e> {public object[] data = null; private int maxSize; Queue capacity private int rear;//queue end, allow insert private int front;//queue header, allow delete private int size=0;
    Queue current length public loopqueue () {this (10);
            Public loopqueue (int initialsize) {if (initialsize >= 0) {this.maxsize = InitialSize;
            data = new Object[initialsize];
        Front = rear = 0;
        else {throw new RuntimeException ("initialization size cannot be less than 0:" + initialsize);
    }///Null public boolean empty () {return size = = 0; }//Insert public boolean Add (e e) {if (size = = maxSize) {throw new RuntimeException ("queue is full, cannot be inserted into the new element.
        ");
            else {data[rear] = e;
            Rear = (rear + 1)%maxsize;
            Size + +;
        return true; }///Return team first element, but do not delete public E peek () {if (empty ()) {throw nEW runtimeexception ("Null queue exception.")
        ");
        else {return (E) Data[front]; }//OUT Team Public E poll () {if (empty ()) {throw new runtimeexception ("Null queue exception.")
        ");
            else {e value = (e) data[front];//Preserve the value of the front element of the queue data[front] = null;//release elements of the front end of the queue  Front = (front+1)%maxsize;
            The team's first pointer plus 1 size--;
        return value;
    }///Queue Length public int length () {return size;
        //Empty the loop queue public void Clear () {Arrays.fill (data, NULL);
        size = 0;
        Front = 0;
    Rear = 0; }
}

Chained storage structure implementation of queues

public class Linkqueue<e> {//Chain stack node private class Node<e> {e E;

        Node<e> Next;
            Public node () {} public node (e E, Node next) {this.e = E;
        This.next = Next; The private node front;//queue header allows the deletion of the private node rear;//queue tail, allowing the insertion of private int size;
        Queue current length public linkqueue () {front = null;
    Rear = NULL;
      }//Null public boolean empty () {return size==0; }//Insert public boolean Add (e e) {if (empty ()) {//If queue is empty front = new Node (E,nul
          l);//Only one node, front, rear all point to the node rear = front;
              }else{node<e> newNode = new node<e> (E, NULL); Rear.next = NewNode; Let the tail node next point to the new node rear = NewNode;
          Take the new node as the new tail node size + +;
      return true; //Returns the first element of the team, but does not delete the public node< E> Peek () {if (empty ()) {throw new runtimeexception ("Null queue exception.")
          ");
          }else{return front; }//OUT Team Public node<e> poll () {if (empty ()) {throw new Runtimeexcep tion ("Empty queue exception.")
          ");
              }else{node<e> value = front;//Get queue header element front = front.next;//Let front refer to the next element of the original queue header element Value.next = null;
              Releases the next reference size of the original queue header element--;
          return value;
      }///Queue Length public int length () {return size; }
}

Implement queue structure based on LinkedList

The 
/** * uses the Java.util.Queue interface, with its underlying connection to a linkedlist (two-terminal queue) instance.
* * Import java.util.LinkedList;

Import Java.util.Queue;
    
    public class Queuelist<e> {private queue<e> Queue = new linkedlist<e> ();
    Inserts the specified element into this queue (if it is immediately feasible and does not violate the capacity limit), returns true on success,//If no space is currently available, throw illegalstateexception.
    Public boolean Add (E. e) {return queue.add (e);
    //Get, but not remove the header from this queue.
    Public E-Element () {return queue.element ();
    ///Inserts the specified element into this queue (if it is immediately feasible and does not violate the capacity limit), when using a capacity-constrained queue,//This method is usually better than add (E), which may not be able to insert an element, but simply throw an exception.
    Public Boolean offer (E e) {return queue.offer (e);
    //Get but do not remove headers for this queue, or null public E peek () {return Queue.peek () If this queue is empty;
    //Get and remove the header of this queue, or null public E poll () {return queue.poll () If this queue is empty;
    //Get and remove the header public E-remove () {return queue.remove () for this queue;
    }//Null public boolean empty () {return queue.isempty (); }
}

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.