1 18 package org.apache.batik.util; 19 20 24 public class DoublyLinkedList { 25 26 29 public static class Node { 30 private Node next = null; 31 private Node prev = null; 32 33 public final Node getNext() { return next; } 34 public final Node getPrev() { return prev; } 35 36 protected final void setNext(Node newNext) { next = newNext; } 37 protected final void setPrev(Node newPrev) { prev = newPrev; } 38 39 42 protected final void unlink() { 43 if (getNext() != null) 44 getNext().setPrev(getPrev()); 45 if (getPrev() != null) 46 getPrev().setNext(getNext()); 47 48 setNext(null); 49 setPrev(null); 50 } 51 52 57 protected final void insertBefore(Node nde) { 58 if (this == nde) return; 60 61 if (getPrev() != null) 62 unlink(); 63 64 if (nde == null) { 66 setNext(this); 68 setPrev(this); 69 } else { 70 setNext(nde); 71 setPrev(nde.getPrev()); 72 nde.setPrev(this); 73 if (getPrev() != null) 74 getPrev().setNext(this); 75 } 76 } 77 } 78 79 80 private Node head = null; 81 private int size = 0; 82 83 public DoublyLinkedList() {} 84 85 88 public synchronized int getSize() { return size; } 89 90 93 public synchronized void empty() { 94 while(size > 0) pop(); 95 } 96 97 101 public Node getHead() { return head; } 102 106 public Node getTail() { return head.getPrev(); } 107 108 112 public void touch(Node nde) { 113 if (nde == null) return; 114 nde.insertBefore(head); 115 head = nde; 116 } 117 118 public void add(int index, Node nde) { 119 if (nde == null) return; 120 if (index == 0) { 121 nde.insertBefore(head); 123 head = nde; 124 } else if (index == size) { 125 nde.insertBefore(head); 128 } else { 129 Node after = head; 130 while (index != 0) { 131 after = after.getNext(); 132 index--; 133 } 134 nde.insertBefore(after); 135 } 136 size++; 137 } 138 139 145 public void add(Node nde) { 146 if (nde == null) return; 147 nde.insertBefore(head); 148 head = nde; 149 size++; 150 } 151 152 159 public void remove(Node nde) { 160 if (nde == null) return; 161 if (nde == head) { 162 if (head.getNext() == head) 163 head = null; else 165 head = head.getNext(); 166 } 167 nde.unlink(); 168 size--; 169 } 170 171 175 public Node pop() { 176 if (head == null) return null; 177 178 Node nde = head; 179 remove(nde); 180 return nde; 181 } 182 183 187 public Node unpush() { 188 if (head == null) return null; 189 190 Node nde = getTail(); 191 remove(nde); 192 return nde; 193 } 194 195 196 197 200 public void push(Node nde) { 201 nde.insertBefore(head); 202 if (head == null) head = nde; 203 size++; 204 } 205 206 209 public void unpop(Node nde) { 210 nde.insertBefore(head); 211 head = nde; 212 size++; 213 } 214 } 215 216 | Popular Tags |