|
1 | | -package lesson7;public class DynamicList { |
| 1 | +package lesson7; |
| 2 | + |
| 3 | +public class DynamicList { |
| 4 | + private int size; |
| 5 | + private Node first; |
| 6 | + private Node last; |
| 7 | + |
| 8 | + public void push(Integer value) { |
| 9 | + if (first == null) { // push 1st element |
| 10 | + first = new Node(value, null, null); |
| 11 | + } else if (last == null) { // push 2nd element |
| 12 | + last = first; |
| 13 | + first = new Node(value, null, last); |
| 14 | + first.pred = first; |
| 15 | + last.pred = first; |
| 16 | + } else { // push 3rd and other(s) |
| 17 | + Node newFirst = new Node(value, null, first); |
| 18 | + first.pred = newFirst; |
| 19 | + first = newFirst; |
| 20 | + } |
| 21 | + size++; |
| 22 | + } |
| 23 | + |
| 24 | + public void offer(Integer value) { |
| 25 | + if (first == null) { // offer 1st element |
| 26 | + first = new Node(value, null, null); |
| 27 | + } else if (last == null) { // offer 2nd element |
| 28 | + last = new Node(value, first, null); |
| 29 | + first.next = last; |
| 30 | + } else { // offer 3rd and other(s) |
| 31 | + Node newLast = new Node(value, last, null); |
| 32 | + last.next = newLast; |
| 33 | + last = newLast; |
| 34 | + } |
| 35 | + size++; |
| 36 | + } |
| 37 | + |
| 38 | + // TODO implement poll() |
| 39 | + |
| 40 | + public Integer pop() { |
| 41 | + Integer value = null; |
| 42 | + if (first != null) { |
| 43 | + value = first.value; |
| 44 | + first = first.next; |
| 45 | + if (first != null) { |
| 46 | + first.pred = null; |
| 47 | + if (first.next == null) { |
| 48 | + last = null; |
| 49 | + } |
| 50 | + } |
| 51 | + size--; |
| 52 | + } |
| 53 | + return value; |
| 54 | + } |
| 55 | + |
| 56 | + @Override |
| 57 | + public String toString() { |
| 58 | + StringBuffer sb = new StringBuffer("["); |
| 59 | + if (first != null) { |
| 60 | + Node cursor = first; |
| 61 | + do { |
| 62 | + sb.append(cursor.value); |
| 63 | + cursor = cursor.next; |
| 64 | + if (cursor != null) { |
| 65 | + sb.append(", "); |
| 66 | + } |
| 67 | + } while (cursor != null); |
| 68 | + } |
| 69 | + return sb.append("]").toString(); |
| 70 | + } |
| 71 | + |
| 72 | + private class Node { |
| 73 | + Integer value; |
| 74 | + Node pred; |
| 75 | + Node next; |
| 76 | + |
| 77 | + public Node(Integer value, Node pred, Node next) { |
| 78 | + this.value = value; |
| 79 | + this.pred = pred; |
| 80 | + this.next = next; |
| 81 | + } |
| 82 | + } |
2 | 83 | } |
0 commit comments