(LC)82. Delete duplicate elements in the sorted list II

82. Delete duplicate elements in the sorted list II

There is a linked list arranged in ascending order. Give you the head node head of the linked list. Please delete all nodes in the linked list that have repeated numbers, and only keep the numbers that do not appear repeatedly in the original linked list.

Return a linked list of results also in ascending order.

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]

prompt:

The number of nodes in the linked list is within the range [0, 300]
-100 <= Node.val <= 100 The
question data ensures that the linked list has been arranged in ascending order

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    
    
    public ListNode deleteDuplicates(ListNode head) {
    
    
        if (head == null) {
    
    
            return head;
        }
        ListNode dum = new ListNode(0,head);
        ListNode cur = dum;

        while (cur.next != null && cur.next.next != null) {
    
    
            if (cur.next.val == cur.next.next.val) {
    
    
                int x = cur.next.val;
                while (cur.next != null && cur.next.val == x) {
    
    
                    cur.next = cur.next.next;
                }
            } else {
    
    
                cur = cur.next;
            }
        }

        return dum.next;


    }
}

Guess you like

Origin blog.csdn.net/weixin_45567738/article/details/115215831