Java data Structures-stack of linear tables (sequential stacks and chain stacks)

Source: Internet
Author: User
Tags null null

Definition of stack: (Special linear table)

?? A linear table that is inserted and deleted only at one end of the table. This end of the Allow insertion and deletion is called the top of the stack, and the other end is called the bottom. The empty stack is called when there are no elements in the table.

?? A linear table called LIFO (last in first out), referred to as the LIFO table, or a linear table known as the advanced post-out, called the Filo table.

?? There are two different ways to store stacks: sequential stacks and chain stacks.

Sequential Stacks:

    • As with the sequential table, the sequential stack also uses arrays to hold data elements;
    • In order to ensure the position of the bottom of the stack, the position of the array subscript 0 is used as the stack bottom of the sequential stack.
    • The maximum value of the stack-top pointer is capacity (stack capacity)-1;
    • When the stack is an empty stack, the top pointer of the stack is indicated by-1.

The following chart (from demonstrates:

For sequential stacks, the stack operation of the data elements is explained as follows:

    1. Stack top pointer top first self-increment 1, to the need to stack the elements to make up memory space;
    2. Then assign a value to the array element of the top corresponding to data[top] = e. Size plus 1

The operation of the stack is reversed, as follows:

    1. First, the value of the array element corresponding to the stack top pointer is obtained;
    2. Then the top of the stack pointer top minus 1. Size minus 1

Here is my Java code implementation:

Package com.phn.stack;/** * @author Pan Hainan * @Email [email protected] * @TODO order stack * @date July 20, 2015 */public class Foar    raystack<e> {//Initialize the storage capacity of the default stack private static final int defualt_capacity = 100;    The array that stores the data elements in the stack private object[] data = null;    The actual size of the stack, private int size;    stack top pointer private int top;    The actual capacity of the stack is private int capacity;    /** * @TODO parameterless constructor, initialize stack */public foarraystack () {this (defualt_capacity);         }/** * @TODO with parameter constructor, initialize stack * @param initialcapacity initialization Stack capacity */public foarraystack (int initialcapacity) {        this.capacity = initialcapacity; = new Object[initialcapacity];        this.size = 0; = this.size-1; }/** * @TODO Press the data element into the stack * @param e data element * @return True */public boolean push (E e) {This.vali        Datecapacity ();;[top]=e;        this.size++;    return true;    }/** * @TODO Verify that the actual size of the stack has reached the limit of the actual capacity of the stack */private void validatecapacity () {if ( {throw new RuntimeException ("This stack is full !        Maximum capacity = "+this.capacity");            }}/** * @TODO gets the top element of the stack and does not pop it to the stack * @return e data element */Public e peek () {if (This.isempty ()) { throw new RuntimeException ("This stack is empty stack!")        ");            }else{Object e = new Object ();            e =[];        Return (e) e;        }}/** * @TODO get the top element of the stack and pop up the stack * @return e data element */Public e pop () {e E = This.peek ();;        this.size--;    return e; }/** * @TODO empty stack * @return true */public boolean clear () {while (>=0) {thi  []=null;  ;        this.size--;    } return true;        } @Override Public String toString () {stringbuffer sb = new StringBuffer ("[");           if (!=-1) {sb.append ([]); int temp =;                while (temp>=0) {sb.append (","[temp]);            temp--;        }} sb.append ("]");    return sb.tostring (); }/** * @TODO to determine if the stack is empty * @return true null or FALSE is not empty */public boolean isEmpty () {//or length for if (this.t        Op==-1) {return true;    } return false;    }/** * The actual size of the @TODO stack * @return */public int size () {return this.size; }}

My Test code:

package com.phn.stack;/** * @author 潘海南 * @Email [email protected] * @TODO 顺序栈测试 * @date 2015年7月20日 */public class FOArrayStackTest {    public static void main(String[] args) {        FOArrayStack<String> foas = new FOArrayStack<String>(6);        foas.push("元素1");        foas.push("元素2");        foas.push("元素3");        foas.push("元素4");        foas.push("元素5");        System.out.println(foas);        foas.pop();        System.out.println(foas);        String s = foas.peek();        System.out.println(s);        System.out.println(foas);        foas.clear();        System.out.println(foas);        System.out.println(foas.isEmpty());    }}

Test results:

The following is an extension of the sequential stack, two stacks of shared space:
?? Sequential stacks have a one-way extension, in a program if you use a two stack with the same data type, you can consider using an array to store the two stacks, where the stack of stack 1 is set at the beginning of the array, stack 2 of the stack is set at the end of the array, two stacks from their respective endpoints to the middle of the array extension, Overflow occurs only when the top of the stack on the two stack encounters at a certain point in the array space. Stack 1 in the stack operation when the top pointer top1++, the stack operation top1–, stack 2 in the stack operation when the top pointer top2–, when the stack operation top2++.

Link Stacks:

    • Similar to a single linked list, except that the chain stack can only insert data from the top of the stack;
    • So you can use the head pointer of the single-linked list as the stack top pointer, and remove the head node of the single-linked list, so that the chain stack is obtained.
    • Chain stacks of different sequential stacks, there is no capacity limit of the stack, there is no full situation. The empty chain stack is defined as a stack-top pointer pointing to null NULL.

For the link stack, the insert (push stack) operation push is interpreted as follows:

    1. Place the data element that you want to insert into a newly established node temp, and point the next of temp to Topnode;
    2. Assigns a value of Topnode to temp. Size plus 1

Delete (eject) Action Pop explained as follows:

    1. Remove the Topnode data element e;
    2. Then point the Topnode to the next node of topnode; size minus 1.

Here is my Java implementation code:

Package com.phn.stack;/** * @author Pan Hainan * @Email [email protected] * @TODO Link stack * @date July 20, 2015 */public class Folin    kedstack<e> {//stack top pointer private folinkednode<e> topnode = null;    The length of the stack is private int size;    /** * @TODO parameterless constructor, initialize the link stack */public folinkedstack () {this.size = 0;    }/** * @TODO Gets the length of the stack * @return */public int size () {return this.size; }/** * @TODO Press the data element into the stack * @param e The data element to be pressed in * @return true */public boolean push (E e) {Foli        nkednode<e> temp = new folinkednode<e> ();        Temp.sete (e);        Temp.addnext (This.topnode);        This.topnode = temp;        this.size++;    return true;            }/** * @TODO get the top element of the stack, and there is no popup, there is the data element in the stack * @return e obtained */public e peek () {if (This.isempty ()) { throw new RuntimeException ("The chain stack is empty!")        ");            }else{e = This.topNode.getE ();        return e; }}/** * @TODOPop up the stack top data element, not on the stack * @return e popup data element */Public e pop () {e E = This.peek ();        This.topnode =;        this.size--;    return e; }/** * @TODO stack is empty * @return true null or FALSE NOT NULL */public boolean isEmpty () {if (This.topnode==nul        L) {return true;    } return false;        } @Override Public String toString () {stringbuffer sb = new StringBuffer ("[");            if (this.topnode!=null) {sb.append (This.topNode.getE ());            Folinkednode<e> temp =new folinkednode<e> ();            temp =;                while (Temp!=null) {sb.append ("," +temp.gete ());            temp =;        }} sb.append ("]");    return sb.tostring (); }}

Link Stack Node class:

package com.phn.stack;public class FOLinkedNode<E> {        private E e;// 结点中存放的数据        FOLinkedNode() {        }        FOLinkedNode(E e) {            this.e = e;        }        FOLinkedNode<E> next;// 用来指向该结点的下一个结点        // 设置下一节点的值        void addNext(FOLinkedNode<E> node) {            next = node;        }        public E getE() {            return e;        }        public void setE(E e) {            this.e = e;        }        @Override        public String toString() {            return e.toString();        }    }

Here is my test code:

public static void main(String[] args) {        FOLinkedStack<String> fols = new FOLinkedStack<String>();        System.out.println(fols.isEmpty());        fols.push("元素1");        System.out.println(fols);        System.out.println(fols.size());        System.out.println(fols.peek());        System.out.println(fols);        System.out.println(fols.pop());        System.out.println(fols.isEmpty());        System.out.println(fols);        System.out.println(fols.size());        fols.push("元素4");        fols.push("元素2");        fols.push("元素5");        fols.push("元素3");        fols.push("元素6");        System.out.println(fols);        System.out.println(fols.size());        System.out.println(fols.isEmpty());    }


Comparison of sequential stacks and chain stacks:

    1. Both stacks are "advanced after-out" (or called "LIFO") features, can only operate at the top of the stack, so the time complexity is constant O (1);
    2. Sequential stack initialization needs to allocate storage space, the allocation is too large to waste, too small overflow;
    3. The chain stack initialization does not require allocating space, but it needs to allocate a pointer field, there is a structural overhead, but there is no length limit.

Application recommendations:
?? If the use of the stack element changes unpredictable, sometimes very small, sometimes very large, then it is best to use the chain stack, conversely, if its change in the controllable range, it is recommended to use a sequential stack is better.

The reason for using the stack: the introduction of the stack simplifies the design of the problem, divided the different levels of attention, so that the scope of thinking narrowed, more focused on the core of the problem we want to solve.

Copyright NOTICE: This article for Bo Master original article, if you need to reprint please specify the source and attached link, thank you.

Java data Structures-stack of linear tables (sequential stacks and chain stacks)

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: 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.