publicMyLinkedList() { size = 0; head = newListNode(0); } publicintget(int index) { if(index < 0 || index >= size){ return -1; } ListNodecur= head; for(inti=0; i <= index; i++){ cur = cur.next; } return cur.val; } publicvoidaddAtHead(int val) { addAtIndex(0, val); } publicvoidaddAtTail(int val) { addAtIndex(size, val); } publicvoidaddAtIndex(int index, int val) { if(index < 0 || index > size){ return; } index = Math.max(0, index); size++; ListNodepre= head; for(inti=0; i < index; i++){ pre = pre.next; } ListNodeadd=newListNode(val); add.next = pre.next; pre.next = add; } publicvoiddeleteAtIndex(int index) { if(index < 0 || index >= size){ return; } size--; if(index == 0){ head = head.next; return; } ListNodepre= head; for(inti=0; i < index; i++){ pre = pre.next; } pre.next = pre.next.next; } }
/** * Your MyLinkedList object will be instantiated and called as such: * MyLinkedList obj = new MyLinkedList(); * int param_1 = obj.get(index); * obj.addAtHead(val); * obj.addAtTail(val); * obj.addAtIndex(index,val); * obj.deleteAtIndex(index); */