Demonstrating a stack implemented as a list : Your Stack « Collections « Java Tutorial






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();
    theStack.pop();

    System.out.println(theStack);
  }
}
{40} {20} 
{80} {60} {40} {20} 
{40} {20}








9.52.Your Stack
9.52.1.A stack allows access to only one data item: the last item inserted
9.52.2.Using stack to reverse a string
9.52.3.Stack Example: Delimiter Matching
9.52.4.Demonstrating a stack implemented as a list