classListNode{int val;
ListNode next;publicListNode(){}publicListNode(int val){this.val = val;}}classMyLinkedList{// 定义成员变量,构造函数int size;
ListNode head;publicMyLinkedList(){
size =0;// 这里一定要给 head 初始化一个对象
head =newListNode();}/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */publicintget(int index){if(index <-1|| index > size -1)return-1;
ListNode cur = head.next;for(int i =0; i < index; i++){
cur = cur.next;}return cur.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){addAtIndex(0,val);}/** Append a node of value val to the last element of the linked list. */publicvoidaddAtTail(int val){addAtIndex(size,val);}/** 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|| index > size)return;
ListNode node =newListNode(val);
ListNode pred = head;for(int i =0; i < index; i++){
pred = pred.next;}
node.next = pred.next;
pred.next = node;
size++;}/** Delete the index-th node in the linked list, if the index is valid. */publicvoiddeleteAtIndex(int index){if(index <-1|| index > size)return;
ListNode pred = head;for(int i =0; i < index; i++){
pred = pred.next;}
pred.next = pred.next.next;
size--;}}classtest{publicstaticvoidmain(String[] args){
MyLinkedList mll =newMyLinkedList();
mll.addAtHead(3);
mll.addAtHead(2);
mll.addAtHead(1);
System.out.println(mll.size);
System.out.println(mll.get(0));
mll.deleteAtIndex(0);
System.out.println(mll.get(1));}}