LinkedStack.java 556 B

123456789101112131415161718192021222324252627282930313233
  1. public class LinkedStack<E> {
  2. Node top;
  3. class Node {
  4. E element;
  5. Node next;
  6. }
  7. public void push(E element) {
  8. Node newNode = new Node();
  9. newNode.element = element;
  10. newNode.next = top;
  11. top = newNode;
  12. }
  13. public E pop() {
  14. if (top == null) {
  15. return null;
  16. }
  17. E data = top.element;
  18. top = top.next;
  19. return data;
  20. }
  21. public E peek() {
  22. if (top == null) {
  23. return null;
  24. }
  25. return top.element;
  26. }
  27. }