Chain Stack
Stack with chained Storage Structure
The time complexity of the push (), pop (), and peek () methods is O (1)
Java implementation:
Package com. ds. stack; public class external stack <T> {/*** title: single-chain table class ** @ author zhb ** @ param <T> */private class Node <T> {public T data; // The data field stores the data element public Node <T> next; // The address field references the successor Node/*** to construct the Node. data specifies the data element, next specify the successor Node ** @ param data * @ param next */public Node (T data, Node <T> next) {this. data = data; this. next = next;} public Node () {this (null, null) ;}} Node <T> top = new Node <T> ();/ /The top node of the stack, public writable stack () {this. top = null;} // determines whether it is a public boolean isEmpty () {return this. top = null;} // element x public void push (T x) {if (x! = Null) this. top = new Node <T> (x, this. top) ;}// the output stack. The public T pop () {if (isEmpty () {return null;} T temp = this. top. data; this. top = this. top. next; return temp;} // retrieve the top element of the stack. The public T peek () {return this. top = null? Null: this. top. data;} public static void main (String [] args) {consumer stack <String> stack = new consumer stack <String> (); stack. push ("Java"); stack. push ("Php"); stack. push ("C ++"); stack. push ("C #"); System. out. println (stack. pop (); System. out. println (stack. peek (); System. out. println (stack. isEmpty ());}}
Running result:
C++C++false
If you have any questions, feel free to contact us!
This article from the "CEO Road" blog, please be sure to keep this source http://zhaohaibo.blog.51cto.com/7808533/1288760