classMyLinkedList{privateclassNode{Node next;int val;publicNode(int val){this.next =null;this.val = val;}}Node head;Node tail;int size;publicMyLinkedList(){
head =null;
tail = head;
size =0;}publicintget(int index){// Empty or index out of bound or invalid indexif(size ==0|| index >= size || index <0)return-1;// Get the nodeNode res = head;while(index >0){
res = res.next;--index;}return res.val;}publicvoidaddAtHead(int val){Node newHead =newNode(val);if(size ==0){
head = newHead;
tail = head;}else{// Connect with the old head
newHead.next = head;// Change the head
head = newHead;}++size;}publicvoidaddAtTail(int val){Node newTail =newNode(val);if(size ==0){
head = newTail;
tail = newTail;}else{// old tail -> newTail
tail.next = newTail;// switch the tail to the latest tail
tail = newTail;}++size;}publicNodegetNodeAt(int index){Node cur = head;while(index-->0){
cur = cur.next;}return cur;}publicvoidaddAtIndex(int index,int val){// Index is invalid, treat it as 0if(index <0)
index =0;// Index = the length of the listelseif(index == size)addAtTail(val);// Index is greater than the lengthelseif(index > size)return;// Index is 0, insert in the headelseif(index ==0)addAtHead(val);else{Node prev =getNodeAt(index -1);Node forward = prev.next;Node cur =newNode(val);
prev.next = cur;
cur.next = forward;++size;}}publicvoiddeleteAtIndex(int index){// Invalid indexif(index <0|| index >= size)return;// Delete the headif(index ==0){deleteHead();}elseif(index == size -1){// Delete the taildeleteTail();}else{Node prev =getNodeAt(index -1);Node cur = prev.next;Node forward = prev.next.next;
prev.next = forward;// Connect 1st and 3rd node
cur.next =null;// Disconnect--size;}}privatevoiddeleteHead(){if(size ==0)return;elseif(size ==1){
head =null;
tail =null;}else{Node newHead = head.next;
head.next =null;// Disconnect
head = newHead;}--size;}privatevoiddeleteTail(){if(size ==0)return;elseif(size ==1){
head =null;
tail =null;}else{// Get the second last nodeNode secLast =getNodeAt(size -2);// Disconnect the last node
secLast.next =null;// Assign new tail
tail = secLast;}--size;}}