Create a stack backed by a list in Java

Description

The following code shows how to create a stack backed by a list.

Example


//w  w  w  .  jav  a  2 s  . c om
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 Main {
  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();
    theStack.pop();

    System.out.println(theStack);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Collection »




Java ArrayList
Java Collection
Java Comparable
Java Comparator
Java HashMap
Java HashSet
Java Iterator
Java LinkedHashMap
Java LinkedHashSet
Java LinkedList
Java List
Java ListIterator
Java Map
Queue
Java Set
Stack
Java TreeMap
TreeSet