82. 删除排序链表中的重复元素 II

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Example 1:

Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]

Example 2:

Input: head = [1,1,1,2,3]
Output: [2,3]

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

删除排序链表中的重复元素II。

时间O(n)

空间O(1)

 

思路:

需要创建一个dummy节点,放在所有需要遍历的节点之前,遍历的时候,

找是否有两个节点的val相同,找到后记下这个val。

再往后遍历的时候,只要遇到这个val就跳过。

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
       ListNode p=new ListNode(0);
       ListNode cur=p;
       cur.next=head;
       while(cur.next!=null && cur.next.next!=null){
           if(cur.next.val==cur.next.next.val){
               int flagVal=cur.next.val;
               while(cur.next!=null&&cur.next.val==flagVal){
                   cur.next=cur.next.next;
               }
           }else{
               cur=cur.next;
           }
       }
       return p.next;

    }
}

  

 

posted @ 2021-08-29 16:09  sherry001  阅读(32)  评论(0编辑  收藏  举报