Advertisement
pexea12

Khanh Stack

Oct 1st, 2015
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.19 KB | None | 0 0
  1.  
  2. public class Stack {
  3.  
  4.         private Node first = null;
  5.         private class Node
  6.         {
  7.             String item;
  8.             Node next = null;
  9.         }
  10.  
  11.         public boolean isEmpty() {
  12.             return first == null;
  13.         }
  14.        
  15.         public void push(String item)
  16.         {
  17.             Node oldfirst = first;
  18.             first = new Node();
  19.             first.item = item;
  20.             first.next = oldfirst;
  21.         }
  22.         public void pop()
  23.         {
  24.             if(isEmpty()){
  25.                 System.out.print("Stack underflow");
  26.                 return;
  27.             }
  28.             String item = first.item;
  29.             first = first.next;
  30.         }
  31.        
  32.         public String peek(){
  33.             if(isEmpty())
  34.                 System.out.print("Stack underflow");
  35.             return first.item;
  36.         }
  37.  
  38.  
  39.     public static void main(String[] args) {
  40.         Stack list = new Stack();
  41.         list.push("co");
  42.         list.push("bao");
  43.         list.push("gio");
  44.         list.push("em");
  45.         list.push("nghi");
  46.         list.push("nghi");
  47.         list.push("ve");
  48.         list.push("anh");
  49.        
  50.         while (!list.isEmpty()) {
  51.             System.out.println(list.peek());
  52.             list.pop();
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement