public class Node { private int data; private Node link; public Node() { data = 0; link = null; } public int getData() { return data; } public Node getLink() { return link; } public void setData(int d) { data = d; } public void setLink(Node l) { link = l; } }
public class List { private Node head; private int count; public List() { head = null; count = 0; } public boolean isEmpty() { return (count == 0); } public int getSize() { return count; } public int getElement(int index) { if(index < 0 || index > count) return -1; Node walker = head; for(int i = 0; i < index; i++) walker = walker.getLink(); return walker.getData(); } public String toString() { String str = "["; Node walker = head; while(walker != null) { str = str + " " + walker.getData(); walker = walker.getLink(); } return str+" ]"; } public boolean search(int element) { Node walker = head; while(walker != null && walker.getData() != element) walker = walker.getLink(); if(walker == null) return false; else return true; } public boolean insert(int element, int index) { if(index < 0 || index > count) return false; Node newNode = new Node(); newNode.setData(element); if(index == 0) { newNode.setLink(head); head = newNode; count++; return true; } Node walker = head; for(int i = 0; i < index-1; i++) walker = walker.getLink(); newNode.setLink(walker.getLink()); walker.setLink(newNode); count++; return true; } public boolean delete(int index) { if(index < 0 || index > count-1) return false; if(index == 0) { head = head.getLink(); count--; return true; } Node walker = head; for(int i = 0; i < index-1; i++) walker = walker.getLink(); walker.setLink(walker.getLink().getLink()); count--; return true; } }
public class Stack extends List { public Stack() { super(); } public int top() { return getElement(0); } public boolean push(int e) { return insert(e, 0); } public boolean pop() { return delete(0); } }
public class StackTest { public static void main(String args[]) { Stack s = new Stack(); //push for(int i = 0; i < 11; i++) s.push(i); //toString System.out.println(s); //pop while(!s.isEmpty()) { s.pop(); System.out.println(s); } } }