publicclassMyLinkedList{ privateclassListNode{ publicint val; public ListNode next; publicListNode(int x){ val = x; next = null; } } private ListNode myLinkedList; /** Initialize your data structure here. */ publicMyLinkedList(){ myLinkedList = null; } /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ publicintget(int index){ if (null == myLinkedList) { return -1; } int i = 0; ListNode currNode = myLinkedList; while (currNode != null) { if (i == index) { return currNode.val; } currNode = currNode.next; ++i; } return -1; } /** 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){ ListNode newNode = new ListNode(val); ListNode oldHeadNode = myLinkedList; newNode.next = oldHeadNode; myLinkedList = newNode; } /** Append a node of value val to the last element of the linked list. */ publicvoidaddAtTail(int val){ ListNode newNode = new ListNode(val); // first node if (null == myLinkedList) { myLinkedList = newNode; } ListNode preNode = null; ListNode currNode = myLinkedList; while (currNode != null) { preNode = currNode; currNode = currNode.next; } preNode.next = newNode; } /** 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 < 0) { return; } if (0 == index) { this.addAtHead(val); return; } // linked list is empty, but index is greater than the length if (null == myLinkedList) { return; } ListNode preNode = null; ListNode currNode = myLinkedList; int i = 0; while (currNode != null) { if (i == index) { break; } preNode = currNode; currNode = currNode.next; ++i; } // when the index in linked list, then i == index, other is the length if (index == i) { ListNode newNode = new ListNode(val); newNode.next = preNode.next; preNode.next = newNode; } return; } /** Delete the index-th node in the linked list, if the index is valid. */ publicvoiddeleteAtIndex(int index){ if (index < 0) { return; } if (null == myLinkedList) { return; } ListNode preNode = null; ListNode currNode = myLinkedList; while (currNode != null) { if (0 == index) { if (preNode != null) { // find index node preNode.next = currNode.next; } else { // first node myLinkedList = currNode.next; } currNode = null; break; } preNode = currNode; currNode = currNode.next; --index; } } }