|
| 1 | +public class LinkedListNode { |
| 2 | + public byte data; |
| 3 | + protected LinkedListNode next; |
| 4 | + |
| 5 | + public LinkedListNode(byte data, LinkedListNode next) { |
| 6 | + this.data = data; |
| 7 | + this.next = next; |
| 8 | + } |
| 9 | +} |
| 10 | + |
| 11 | +public class LinkedList { |
| 12 | + private LinkedListNode head; |
| 13 | + private int length; |
| 14 | + |
| 15 | + public LinkedList() { |
| 16 | + this.head = null; |
| 17 | + this.length = 0; |
| 18 | + } |
| 19 | + |
| 20 | + public LinkedListNode getHead() { |
| 21 | + return this.head; |
| 22 | + } |
| 23 | + |
| 24 | + public int getLength() { |
| 25 | + return this.length; |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Insert new data at a specified index, shifting existing node at the index |
| 30 | + * and all nodes after it to the right. |
| 31 | + * |
| 32 | + * <p> |
| 33 | + * O(1) complexity for inserting at the head, O(i) complexity for other cases. |
| 34 | + * @param data |
| 35 | + * @param index A valid index for the new node that is between 0 and |
| 36 | + * <code>this.length</code> (inclusive). |
| 37 | + * @return |
| 38 | + */ |
| 39 | + public LinkedListNode insert(byte data, int index) { |
| 40 | + if (index < 0 || index > this.length) return null; |
| 41 | + |
| 42 | + LinkedListNode newNode = new LinkedListNode(data, null); |
| 43 | + |
| 44 | + if (index == 0) { |
| 45 | + if (this.head != null) newNode.next = this.head; |
| 46 | + this.head = newNode; |
| 47 | + |
| 48 | + return newNode; |
| 49 | + } |
| 50 | + |
| 51 | + LinkedListNode prevNode = this.head; |
| 52 | + |
| 53 | + for (int i = 1; i < index; i++) |
| 54 | + prevNode = prevNode.next; |
| 55 | + |
| 56 | + if (index != this.length) |
| 57 | + newNode.next = prevNode.next; |
| 58 | + |
| 59 | + prevNode.next = newNode; |
| 60 | + this.length++; |
| 61 | + |
| 62 | + return newNode; |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Deletes the node at the specified index. |
| 67 | + * |
| 68 | + * <p> |
| 69 | + * O(n) complexity |
| 70 | + * @param index |
| 71 | + * @return |
| 72 | + */ |
| 73 | + public LinkedListNode delete(int index) { |
| 74 | + if (index < 0 || index >= this.length || this.length == 0) return null; |
| 75 | + |
| 76 | + LinkedListNode prevNode = this.head; |
| 77 | + |
| 78 | + for (int i = 1; i < index; i++) |
| 79 | + prevNode = prevNode.next; |
| 80 | + |
| 81 | + LinkedListNode node = prevNode.next; |
| 82 | + prevNode.next = node.next; |
| 83 | + |
| 84 | + return node; |
| 85 | + } |
| 86 | +} |
0 commit comments