牛客网高频算法题系列-BM16-删除有序链表中重复元素-II升序,删除链表中所有重复的元素,只保留原链表中只出现一次的元素。见原标题:BM16DeleteDuplicateElementsinanOrderedLinkedList-II解题一:链表遍历首先考虑特殊情况,如果链表为空或者只有一个节点,则不会有重复元素,返回原始链表。否则遍历链表判断是否有重复元素。过程如下:首先,由于头节点也可能重复,所以使用一个虚拟的头节点dummyNode;point,count记录该节点的元素的重复次数,初始为1;然后从原链表的第二个节点开始遍历;如果当前节点的值与lastNonRedundantNode不同,则判断lastNonRedundantNode出现的次数,如果只通过一次,则为非重复节点,更新pre;否则,pre不会更新。更新lastNonRedundantNode并将count重置为1。如果当前节点的值与lastNonRedundantNode相同,则将count加1。最后判断最后一个节点出现的次数。如果计数为1,它也是一个唯一节点。最后,返回新构造的具有唯一元素的链表。codepublicclassBm016{/***删除有序链表-II中的重复元素**@paramheadListNodeclass*@returnListNodeclass*/publicstaticListNodedeleteDuplicates(ListNodehead){//如果链表为空或者只有A节点,不会有重复元素,返回原链表if(head==null||head.next==null){returnhead;}//因为头节点也可能重复,所以使用衣蛾虚拟头节点ListNodedummyNode=newListNode(-1);//pre不是新构造的链表节点,有非重复元素//lastNonRedundantNode是最后一个非重复节点ListNodepre=dummyNode,lastNonRedundantNode=head,next=head.下一个;//count为最后一个非重复元素的重复次数intcount=1;//遍历链表while(next!=null){//如果当前节点的值与lastNonRedundantNode不同,判断lastNonRedundantNode出现的次数,如果只出现一次,则为非重复节点//updatepre,否则不更新pre//更新lastNonRedundantNode,并将count重置为1if(next.val!=lastNonRedundantNode.val){if(count==1){pre.next=newListNode(lastNonRedundantNode.val);pre=pre.next;}lastNonRedundantNode=下一个;计数=1;}else{//如果当前节点的值与lastNonRedundantNode相同,则计数加1count++;}next=next.next;}//最后一个节点Point需要判断出现的次数if(count==1){pre.next=newListNode(lastNonRedundantNode.val);}返回dummyNode.next;}publicstaticvoidmain(String[]args){ListNodehead=ListNode.testCase6();System.out.println("原链表为");ListNode.print(head);System.out.println("有序链表中删除重复元素后的链表为");ListNode.print(deleteDuplicates(head));}}$1.01^{365}≈37.7834343329$$0.99^{365}≈0.02551796445$相信坚持的力量!
