Mega Code Archive

 
Categories / Java Tutorial / Collections
 

Demonstrating a stack implemented as a list

class Link {   public int iData;   public Link next;   public Link(int id) {     iData = id;   }   public String toString() {     return "{" + iData + "} ";   } } class LinkList {   private Link first;   public LinkList() {     first = null;   }   public boolean isEmpty() {     return (first == null);   }   public void insertFirst(int dd) {     Link newLink = new Link(dd);     newLink.next = first;     first = newLink;   }   public int deleteFirst() {     Link temp = first;     first = first.next;     return temp.iData;   }   public String toString() {     String str="";     Link current = first;     while (current != null) {       str += current.toString();       current = current.next;     }     return str;   } } class LinkStack {   private LinkList theList;   public LinkStack() {     theList = new LinkList();   }   public void push(int j) {     theList.insertFirst(j);   }   public double pop() {     return theList.deleteFirst();   }   public boolean isEmpty() {     return (theList.isEmpty());   }   public String toString() {     return theList.toString();   } } public class MainClass {   public static void main(String[] args) {     LinkStack theStack = new LinkStack();     theStack.push(20);     theStack.push(40);     System.out.println(theStack);     theStack.push(60);     theStack.push(80);     System.out.println(theStack);     theStack.pop();     System.out.println(theStack);   } } {40} {20} {80} {60} {40} {20} {40} {20}