Guest User

Untitled

a guest
Dec 2nd, 2015
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. public class StackNode<E> {
  2. private E data;
  3. private StackNode<E> next;
  4. public StackNode(E data){
  5. this.data = data;
  6. this.next = null;
  7. }
  8. public StackNode<E> getNext(){
  9. return this.next;
  10. }
  11. public void setNext(StackNode<E> next){
  12. this.next = next;
  13. }
  14. public E getData(){
  15. return this.data;
  16. }
  17. }
  18.  
  19. import java.util.NoSuchElementException;
  20.  
  21. public class Stack<E> {
  22. private StackNode<E> top;
  23. private int size;
  24. public Stack(E data){
  25. StackNode<E> node = new StackNode<E>(data);
  26. this.top = node;
  27. }
  28. public Stack(){
  29. this.top = null;
  30. }
  31. public StackNode<E> peek(){
  32. return this.top;
  33. }
  34. public int getSize(){
  35. return this.size;
  36. }
  37. public void increaseSize(){
  38. this.size++;
  39. }
  40. public void decreaseSize(){
  41. this.size--;
  42. }
  43. public StackNode<E> pop(){
  44. StackNode<E> node = this.top;
  45. this.top = this.top.getNext();
  46. decreaseSize();
  47. return node;
  48. }
  49. public void push(E data){
  50. StackNode<E> node = new StackNode<E>(data);
  51. node.setNext(this.top);
  52. increaseSize();
  53. this.top = node;
  54. }
  55. public void print(){
  56. StackNode<E> node = this.top;
  57. if (node==null){
  58. throw new NoSuchElementException();
  59. }
  60. StringBuilder s = new StringBuilder();
  61. while (node!=null){
  62. s.append(node.getData()+" ");
  63. node=node.getNext();
  64. }
  65. System.out.println(s);
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment