Java Data Structure: 3.2 chain Stack

Source: Internet
Author: User

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

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.