image.png

思路

快慢指针法

code

  1. public ListNode deleteDuplicates(ListNode head) {
  2. //虚拟节点的next指向head 快指针指向head 慢指针指向dummy
  3. ListNode dummy = new ListNode(0),fast =head,slow = dummy;
  4. slow.next = fast; //快慢指针连在一起
  5. while(fast!=null){ //一直到快指针到头
  6. while(fast.next!=null&&fast.val==fast.next.val){
  7. fast = fast.next; //如果值重复 则将fast向后
  8. }
  9. if(slow.next!=fast){ //如果此时没有重复元素,则slow.next=fast
  10. slow.next = fast.next; //将slow跳到fast
  11. fast = fast.next; //将fast向后移动
  12. }else{
  13. slow = slow.next; //如果没有则都相互移动
  14. fast = fast.next;
  15. }
  16. }
  17. return dummy.next;
  18. }