/** Initialize your data structure here. */ publicMyLinkedList(){ Node node = new Node(0); this.head = node; this.tail = node; this.size = 0; } /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ publicintget(int index){ if (index < 0 || index >= this.size) return -1; Node node = head; for (int i = 0; i < index; i++){ node = node.next; } return node.val; } /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ publicvoidaddAtHead(int val){ if (this.size == 0) this.head.val = val; else { Node tmp = new Node(val); tmp.next = head; this.head = tmp; } this.size++; } /** Append a node of value val to the last element of the linked list. */ publicvoidaddAtTail(int val){ if (this.size == 0) this.tail.val = val; else { Node tmp = new Node(val); this.tail.next = tmp; this.tail = tmp; } this.size++; } /** * Add a node of value val before the index-th node in the linked list. * If index equals to the length of linked list, * the node will be appended to the end of linked list. * If index is greater than the length, the node will not be inserted. */ publicvoidaddAtIndex(int index, int val){ if (index > this.size) return;
if (index == this.size) { addAtTail(val); } elseif (index <= 0) { addAtHead(val); } else { Node node = new Node(val); Node tmp = head; for(int i = 1; i < index; i++) { tmp = tmp.next; } node.next = tmp.next; tmp.next = node; this.size++; } } /** Delete the index-th node in the linked list, if the index is valid. */ publicvoiddeleteAtIndex(int index){ if (index < 0 || index >= this.size) return;
if (index == 0) { this.head = this.head.next; } else { Node node = head; for (int i = 1; i < index; i++) { node = node.next; } node.next = node.next.next; if (index == this.size-1) { tail = node; } } this.size--; } }