/** 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. */ public void AddAtIndex(int index, int val) { //Cannot add beyond the index if (index > size) { return; } //Node can be added at the head if negative if (index < 0) { index = 0; } size++; //Find the predecessor of the node to be added ListNode153 prev = head; for (int i = 0; i < index; i++) { prev = prev.next; } //New node ListNode153 nodeToAdd = new ListNode153(val); //insert the node nodeToAdd.next = prev.next; prev.next = nodeToAdd; }
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ public int Get(int index) { if (index < 0 || index >= size) { return(-1); } ListNode153 curr = head; for (int i = 0; i <= index; i++) { curr = curr.next; } return(curr.value); }
/** Delete the index-th node in the linked list, if the index is valid. */ public void DeleteAtIndex(int index) { if (index < 0 || index >= size) { return; } //reduce the count size--; //Find the predecessor for the node to be deleted ListNode153 prev = head; for (int i = 0; i < index; i++) { prev = prev.next; } // delete the node prev.next = prev.next.next; }
/** Initialize your data structure here. */ public MyLinkedList153() { size = 0; head = new ListNode153(0); }