Linear table of Java Data Structures (2)

Source: Internet
Author: User

From here, we will be explaining the Java data structure, is it ready? Let ' s go~~

The data structure model in Java can be divided into several parts:

1. Linear structure

2. Tree-shaped structure

3. Graphic or mesh structure

In the next few, we will explain these data structures separately, mainly through the way of Java code to explain the corresponding structure.

Today's explanation is: Java linear structure

The linear structure of Java data structures

When it comes to linear structures, we can be divided into two categories according to the way they are implemented:

1) linear table of sequential structure

2) linear table of chain structure

3) Stack and queue linear table

For explanations of 1 and 2), please refer to the following address:

The following focuses on stacks and queues in a linear structure.

1. Explanation of the stack of linear structure

The so-called stack is a special linear structure, which is characterized only by allowing us to insert and remove at the end of the linear table. Can be understood as a restricted

Linear table. Adding an element to a linear table we call it into the stack, removing an element from the linear table we call the stack. Really do not understand, Baidu a bit you will know.

The implementation of Java in the JDK is based on the stack (the underlying vector class) and LinkedList (which also implements the Push,pop,peek, etc.), or that sentence, interested in

You can view the source code yourself.

Here we carry out the relevant imitation,

First, the stack and stack operations are modeled by arrays:

    

Package Com.yonyou.test;import java.util.arrays;/** * Test class * @author Little Hao * @ Creation date 2015-3-20 */public class Test {public stat IC void Main (string[] args) {sequencestack<string> stack=new sequencestack<string> (); SYSTEM.OUT.PRINTLN ("The initialization length of the sequential stack is:" +stack.length ()); Stack.push ("Hello"); Stack.push ("World"); Stack.push ("The World of peace"); SYSTEM.OUT.PRINTLN ("the element in the current stack is:" +stack); System.out.println ("Current stack.peek (); The element in is:" +stack.peek ()); System.out.println ("The current element linear table is empty:" +stack.empty ());}} /** * Create a linear stack * Note that this class is thread insecure, do not use in multi-threaded * @author Small Hao * @ Created date 2015-3-20 * @param <T> */class sequencestack<t>{// The default length of the linear stack is 10private int default_size = 10;//Saves the length of the array. private int capacity;//defines when the underlying array is not large enough, the program increments each time the array length is private int capacityincrement = 0;//defines an array to hold the elements of the sequential stack private object[]    elementdata;//saves the current number of elements in the sequential stack private int size = 0;   /** * Create empty sequence stack with default array length */public Sequencestack () {capacity = Default_size;elementdata = new Object[capacity];} /** * Create sequential stacks with an initialization element * @param element */public SeQuencestack (T Element) {this (); elementdata[0] = element;size++;} /** * Create a sequential stack with an array of specified lengths * @param element specifies the first element of the sequence stack * @param initsize Specifies the length of the underlying array in the sequence stack */public sequencestack (T element, int in itsize) {this.capacity = Initsize;elementdata = new Object[capacity];elementdata[0] = element;size++;} /** * Create a sequential stack with an array of specified lengths * @param element specifies the first element of the sequence stack * @param initsize Specifies the length of the underlying array of the sequence stack * @param capacityincrement Specifies the length of the underlying array when the sequence stack If not enough, the underlying array increments each time */public Sequencestack (T element, int initsize, int capacityincrement) {this.capacity = initsize; This.capacityincrement = Capacityincrement;elementdata = new Object[capacity];elementdata[0] = element;size++;} /** * Gets the size of the sequential stack * @return */public int Length () {return size;} /** * into the stack * @param element */public void push (T element) {ensurecapacity (size + 1); elementdata[size++] = element;}  /** * Very troublesome, and poor performance * @param mincapacity */private void ensurecapacity (int mincapacity) {//if the original length of the array is less than the current required length if (mincapacity > Capacity) {if (capacityincrement > 0) {while (Capacity < Mincapacity) {//constant capacity length plus capacityincrement,//until capacity is greater than mincapacity capacity + = Capacityincrement;}} ELSE{//will continue to capacity * 2 until capacity is greater than mincapacity while (capacity < mincapacity) {capacity <<= 1;}} Elementdata = arrays.copyof (elementdata, capacity);}} /** * out of Stack * @return */@SuppressWarnings ("unchecked") public T pop () {t oldValue = (T) elementdata[size-1];//release stack top element ELEMENTDA Ta[--size] = Null;return oldValue;} /** * Returns the top element of the stack, but does not delete the top element of the stack * @return */@SuppressWarnings ("unchecked") public T Peek () {return (T) elementdata[size-1];}     /** * Determine if the sequence stack is empty stack * @return */public boolean empty () {return size = = 0;} /** * empty sequence stack */public void clear () {//assigns all elements of the underlying array to Nullarrays.fill (Elementdata, null); size = 0;} /** * Rewrite tostring */public String ToString () {if (size = = 0) {return ' [] ';} Else{stringbuilder sb = new StringBuilder ("["); for (int i = size-1; i >-1; i--) {sb.append (elementdata[i].tostring () + ",");} int len = Sb.length (); return Sb.delete (Len-2, Len). Append ("]"). toString ();}}

Second, through the chain storage to imitate the stack and the stack operation, the specific content can see the following code:

Package com.yonyou.test;/** * Test class * @author Little Hao * @ Creation date 2015-3-20 */public class Test {public static void main (string[] Ar GS) {linkstack<string> stack=new linkstack<string> (); SYSTEM.OUT.PRINTLN ("The initialization length of the sequential stack is:" +stack.length ()); Stack.push ("Hello"); Stack.push ("World"); Stack.push ("The World of peace"); SYSTEM.OUT.PRINTLN ("the element in the current stack is:" +stack); System.out.println ("Current stack.peek (); The element in is:" +stack.peek ()); System.out.println ("The current element linear table is empty:" +stack.empty ());}} /** * Create a linear stack of chained storage * Note that this class is thread insecure, do not use in multi-threaded * @author Small Hao * @ Created date 2015-3-20 * @param <T> */class linkstack<t>{ Defines an inner class Node,node instance that represents the node of the chain stack. Private class node{//Save node's data private T data;//reference to the next node private node next;//parameterless constructor public node () {}//Initialize all properties of the constructor public No De (T data, Node next) {this.data = Data;this.next = Next;}} Save the stack top element private node top;//Save the number of nodes already contained in the chain private int size;/** * Create empty chain stack */public linkstack () {//empty chain stack, top value is Nulltop = nul l;} /** * Creates a chain stack with the specified data element, which has only one element * @param elements */public Linkstack (T element) {top = new Node (elemenT, null); size++;} /** * Returns the length of the chain stack * @return */public int Length () {return size;} /** * into the stack * @param element */public void push (T Element) {//Let top point to the newly created element, the next reference of the new element points to the original top of the stack element top = new Node (element, top); s ize++;} /** * out of Stack * @return */public T pop () {Node oldtop = top;//Let top refer to the next element of the top of the original stack, top = top.next;//releases the next reference to the top element of the original stack oldtop.next = Null;size--;return Oldtop.data;} /** * Accesses the top element of the stack, but does not delete the top element of the stack * @return */public T Peek () {return top.data;} /** * Determine if the link stack is empty stack * @return */public boolean empty () {return size = = 0;} /** * Empty the link stack */public void clear () {//assigns all elements of the underlying array to Nulltop = Null;size = 0;} /** * Overrides the ToString Method */public String ToString () {///link stack to empty chain stack when if (empty ()) {return "[]";} Else{stringbuilder sb = new StringBuilder ("["); for (Node current = top; Current! = NULL; Current = Current.next) {sb.append (current.data.toString () + ",");} int len = Sb.length (); return Sb.delete (Len-2, Len). Append ("]"). toString ();}}

2. Explanation of the linear structure of the queue

A queue is also a constrained data structure that uses a fixed end to insert elements (the tail of a team) and delete related elements (team heads) at the other end.

Its basic features are "FIFO", and the basic features of the stack are "advanced after-out".

In the Java JDK, the main implementation class is the implementation class of the Dqueue interface Arraydeque (linear) and LinkedList (chained), if interested, check the relevant source code.

The first explanation is the linear storage of queues:

Please see the relevant code for details:

&NBSP;&NBSP;&NBSP;

Package Com.yonyou.test;import java.util.arrays;/** * Test class * @author Little Hao * @ Creation date 2015-3-20 */public class Test {public stat IC void Main (string[] args) {sequencequeue<string> queue=new sequencequeue<string> (); SYSTEM.OUT.PRINTLN ("The initialization length of the queue is:" +queue.length ()); Queue.add ("Hello"); Queue.add ("World"); Queue.add ("Peace");    SYSTEM.OUT.PRINTLN ("the element in the current stack is:" +queue); Queue.remove (); SYSTEM.OUT.PRINTLN ("the element in the current stack is:" +queue); System.out.println ("The current element linear table is empty:" +queue.empty ());}} /** * Create a stored linear queue * Note that this class is thread insecure, do not use in multi-threaded * @author Small Hao * @ Created date 2015-3-20 * @param <T> */class SEQUENCEQUEUE&LT;T&G T The default length of the {///linear queue private int default_size = 16;//Saves the length of the array. private int capacity;//defines an array to hold the elements of the sequential queue private object[] elementdata;//the current number of elements in the Save order queue private int front = 0;private int R Ear = 0;/** * Create empty order queue with default array length */public Sequencequeue () {capacity = Default_size;elementdata = new Object[capacity];} /** * Create sequential queues with an initialization element * @param element */public Sequencequeue (T Element) {this (); elementdata[0] = Element;rear++;}  /** * Creates a sequential queue with an array of specified lengths * @param element specifies the first element in the sequential queue * @param initsize Specifies the length of the underlying array of sequential queues */public sequencequeue (T element, int initsize) {this.capacity = Initsize;elementdata = new Object[capacity];elementdata[0] = element;rear++;} /** * Gets the size of the sequential queue * @return */public int Length () {return rear-front;} /** * Insert Queue * @param element */public void Add (T element) {if (Rear > Capacity-1) {throw new Indexoutofboundsexception (" The queue is full of exceptions ");} elementdata[rear++] = element;} /** * Move Out queue * @return */@SuppressWarnings ("unchecked") public T Remove () {if (empty ()) {throw new Indexoutofboundsexception ( "Empty queue exception");} The value of the element that holds the front side of the queue T OldValue = (t) elementdata[front];//releases the front-side element of the queue elementdata[front++] = Null;return oldValue;} /** * Returns the top element of the queue, but does not delete the top element of the queue * @return */@SuppressWarnings ("unchecked") public T Element () {if (empty ()) {throw new Indexoutofboundsexception ("Empty queue exception");} Return (T) Elementdata[front];} /** * Determine if the order queue is an empty queue * @return */public Boolean empty () {return rear = = Front;} /** Empty order queue * */public void Clear () {//will be the underlying numberAll elements of the group are assigned Nullarrays.fill (elementdata, null); front = 0;rear = 0;} /** * Overrides the ToString Method */public String ToString () {if (empty ()) {return "[]";} Else{stringbuilder sb = new StringBuilder ("["); for (int i = front; I < rear; i++) {sb.append (elementdata[i].tostring () + ",");} int len = Sb.length (); return Sb.delete (Len-2, Len). Append ("]"). toString ();}}

  The second explanation is the cyclic composition of the queue's linear storage:

For the above non-cyclic storage may be a very waste of space, below we will create a corresponding circular link to the concept of the amount, which may effectively save the corresponding space.

Because the loop list can effectively eliminate the phenomenon of fake full oh.

Needless to say, please look at the code:

Package Com.yonyou.test;import java.util.arrays;/** * Test class * @author Little Hao * @ Creation date 2015-3-20 */public class Test {public stat IC void Main (string[] args) {loopqueue<string> queue=new loopqueue<string> (); SYSTEM.OUT.PRINTLN ("The initialization length of the queue is:" +queue.length ()); Queue.add ("Hello"); Queue.add ("World"); Queue.add ("Peace");    SYSTEM.OUT.PRINTLN ("the element in the current stack is:" +queue); Queue.remove (); SYSTEM.OUT.PRINTLN ("the element in the current stack is:" +queue); System.out.println ("The current element linear table is empty:" +queue.empty ());}} /** * Create a sequential stored circular linear queue * Note that this class is thread insecure and do not use * @author Little Hao * @ creation Date 2015-3-20 * @param <T> */class Loopqueue<t&gt ; The default length of the {///circular queue is 16private int default_size = 16;//The length of the array is saved. private int capacity;//defines an array to hold the elements of the looping queue private object[] elementdata;//saves the current number of elements in the loop queue private int front = 0;private int R Ear = 0;/** * Creates an empty loop queue with the default array length */public Loopqueue () {capacity = Default_size;elementdata = new Object[capacity];} /** * Creates a looping queue with an initialization element * @param element */public Loopqueue (T Element) {this (); elementdata[0] = element;rear++;} /** * To specify LongArray of degrees to create a circular queue * @param element specifies the first element in the loop queue * @param initsize Specifies the length of the underlying array of the loop queue */public Loopqueue (T element, int initsize) {thi s.capacity = Initsize;elementdata = new Object[capacity];elementdata[0] = element;rear++;} /** * Gets the size of the loop queue * @return */public int Length () {if (empty ()) {return 0;} Return rear > front? Rear-front:capacity-(front-rear);}  /** * Insert Queue * @param element */public void Add (T element) {if (rear = = front&& Elementdata[front]! = null) {throw new Indexoutofboundsexception ("The queue is full exception");} elementdata[rear++] = element;//If rear has been to the end, then turn head rear = Rear = capacity? 0:rear;} /** * Move Out queue * @return */@SuppressWarnings ("unchecked") public T Remove () {if (empty ()) {throw new Indexoutofboundsexception ( "Empty queue exception");} The value of the element that holds the front side of the queue T OldValue = (t) elementdata[front];//the element that releases the front side of the queue elementdata[front++] = null;//If the front is already at the head, Then turn around front = Front = = capacity? 0:front;return OldValue;} Returns the top element of the queue, but does not delete the top element of the queue @suppresswarnings ("unchecked") public T Element () {if (empty ()) {throw new INDEXOUTOFBOundsexception ("Empty queue exception");} Return (T) Elementdata[front];} Determines whether the loop queue is empty queue public boolean empty () {//rear==front and rear element is nullreturn rear = = front&& Elementdata[rear] = = null;} Empty loop queue public void Clear () {//assigns all elements of the underlying array to Nullarrays.fill (Elementdata, null); front = 0;rear = 0;} Public String toString () {if (empty ()) {return "[]";}  else{//if front < rear, the valid element is the element between front to rear if (front < rear) {StringBuilder SB = new StringBuilder ("["); for (int i = Front; I < rear; i++) {sb.append (elementdata[i].tostring () + ",");} int len = Sb.length (); return Sb.delete (Len-2, Len). Append ("]"). ToString (); If front >= rear, the valid element is the element between front->capacity,//and 0->front else{stringbuilder sb = new StringBuilder ("["); for (int i = front; i < capacity; i++) {Sb.append (elementdata[i].tostring () + ",");} for (int i = 0; i < rear; i++) {Sb.append (elementdata[i].tostring () + ",");} int len = Sb.length (); return Sb.delete (Len-2, Len). Append ("]"). toString ();}}}

  

  

  

Linear table of Java Data Structures (2)

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.