classSolution{publicListNoderemoveElements(ListNode head,int val){while(head!=null&&head.val==val){
head = head.next;}if(head==null)returnnull;ListNode pre = head;ListNode cur = head.next;while(cur!=null){if(cur.val==val){
pre.next = cur.next;}else{
pre = pre.next;}
cur = cur.next;}return head;}}
classLinkedListOne{publicint data;publicLinkedListOne next;publicLinkedListOne(int data,LinkedListOne next){this.data = data;this.next = next;}}classMyLinkedList{publicLinkedListOne head =newLinkedListOne(-1,null);publicMyLinkedList(){}publicintsize(){LinkedListOne cur = head;int count=0;while(cur.next!=null){
cur = cur.next;
count++;}return count;}//获取链表中第 index 个节点的值。如果索引无效,则返回-1。publicintget(int index){LinkedListOne cur =this.head;int length =this.size();if(index<0|| index>=length){return-1;}int count=0;while(count!=index){
cur = cur.next;
count++;}return cur.next.data;}//在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点publicvoidaddAtHead(int val){LinkedListOne cur =this.head;LinkedListOne node =newLinkedListOne(val,cur.next);
cur.next = node;}//将值为 val 的节点追加到链表的最后一个元素publicvoidaddAtTail(int val){LinkedListOne cur =this.head;while(cur.next!=null){
cur = cur.next;}
cur.next =newLinkedListOne(val,null);}//在链表中的第 index 个节点之前添加值为 val 的节点publicvoidaddAtIndex(int index,int val){LinkedListOne cur =this.head;int length =this.size();//如果 index 等于链表的长度,则该节点将附加到链表的末尾if(index==length){this.addAtTail(val);return;}//如果 index 大于链表长度,则不会插入节点if(index>length)return;//如果index小于0,则在头部插入节点if(index<0){this.addAtHead(val);return;}int count=0;while(count!=index){
cur = cur.next;
count++;}LinkedListOne after = cur.next;
cur.next =newLinkedListOne(val,after);}//如果索引 index 有效,则删除链表中的第 index 个节点publicvoiddeleteAtIndex(int index){LinkedListOne cur =this.head;int length =this.size();if(index<0|| index>=length){return;}int count=0;while(count!=index){
cur = cur.next;
count++;}//最后一个节点 if(index==length-1){
cur.next=null;return;}
cur.next = cur.next.next;}}