1 30 31 32 package org.hsqldb.lib; 33 34 43 public class HsqlLinkedList extends BaseList implements HsqlList { 44 45 49 private Node first; 50 51 52 private Node last; 53 54 57 public HsqlLinkedList() { 58 59 first = new Node(null, null); 60 last = first; 61 elementCount = 0; 62 } 63 64 69 public void add(int index, Object element) { 70 71 if (index == size()) { 72 add(element); } 74 75 else if (index > size()) { 78 throw new IndexOutOfBoundsException ("Index out of bounds: " 79 + index + " > " + size()); 80 } else { 81 Node current = getInternal(index); 82 Node newNext = new Node(current.data, current.next); 83 84 current.data = element; 85 current.next = newNext; 86 87 elementCount++; 88 89 if (last == current) { 92 last = newNext; 93 } 94 } 95 } 96 97 101 public boolean add(Object element) { 102 103 last.next = new Node(element, null); 104 last = last.next; 105 106 elementCount++; 107 108 return true; 109 } 110 111 public void clear() { 112 first.next = null; 113 } 114 115 121 public Object get(int index) { 122 return getInternal(index).data; 123 } 124 125 131 public Object remove(int index) { 132 133 if (index >= size()) { 137 throw new IndexOutOfBoundsException ("Index out of bounds: " 138 + index + " >= " + size()); 139 } 140 141 Node previousToRemove; 143 144 if (index == 0) { 145 previousToRemove = first; 146 } else { 147 previousToRemove = getInternal(index - 1); 148 } 149 150 Node toRemove = previousToRemove.next; 153 154 previousToRemove.next = toRemove.next; 155 156 elementCount--; 157 158 if (last == toRemove) { 161 last = previousToRemove; 162 } 163 164 return toRemove.data; 165 } 166 167 172 public Object set(int index, Object element) { 173 174 Node setMe = getInternal(index); 175 Object oldData = setMe.data; 176 177 setMe.data = element; 178 179 return oldData; 180 } 181 182 188 public final int size() { 189 return elementCount; 190 } 191 192 200 protected final Node getInternal(int index) { 201 202 if (index >= size()) { 204 throw new IndexOutOfBoundsException ("Index out of bounds: " 205 + index + " >= " + size()); 206 } 207 208 if (index < 0) { 209 throw new IndexOutOfBoundsException ("Index out of bounds: " 210 + index + " < 0"); 211 } 212 213 if (index == 0) { 214 return first.next; 215 } else if (index == (size() - 1)) { 216 return last; 217 } else { 218 Node pointer = first.next; 219 220 for (int i = 0; i < index; i++) { 221 pointer = pointer.next; 222 } 223 224 return pointer; 225 } 226 } 227 228 235 private static class Node { 236 237 public Node next; 238 public Object data; 239 240 public Node() { 241 next = null; 242 data = null; 243 } 244 245 public Node(Object data) { 246 this.next = null; 247 this.data = data; 248 } 249 250 public Node(Object data, Node next) { 251 this.next = next; 252 this.data = data; 253 } 254 } 255 } 256 | Popular Tags |