Java using generic implementation stack structure sample sharing _java

Source: Internet
Author: User

Thinking Analysis: Since it is a generic implementation of the stack structure, then you can not use the JDK with the stack package, you need to define a stack structure, such as LinkedList.

The code is as follows:

Stack.java:

Copy Code code as follows:

Package cn.edu.xidian.crytoll;
Import java.util.LinkedList;

public class Stack<t> {

Private linkedlist<t> container = new linkedlist<t> ();

public void push (T-t) {
Container.addfirst (t);
}

Public T pop () {
return Container.removefirst ();
}

public Boolean empty () {
return Container.isempty ();
}
}

Stacktest.java:

Copy Code code as follows:

Package cn.edu.xidian.crytoll;

public class Stacktest {
public static void Main (string[] args) {
stack<string> stack = new stack<string> ();
System.out.println ("Add string to Stack:");
System.out.println ("Video learning Java");
System.out.println ("Java");
System.out.println ("Java from Getting Started to mastering (2nd edition)");
Stack.push ("Video learning Java"); Add a string to the stack
Stack.push ("Java"); Add a string to the stack
Stack.push ("Java from Getting Started to mastering (2nd edition)"); Add a string to the stack
SYSTEM.OUT.PRINTLN ("Fetch the string from the stack:");
while (!stack.empty ()) {
System.out.println ((String) Stack.pop ());//Delete all elements of the stack and output
}
}
}

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.