[LeetCode-Java Exercise] 83. Delete duplicate elements in the sorted list (simple)

1. Title description

Insert picture description here

2. Problem solving ideas

Direct method
Since the input list is sorted, we can determine whether it is a duplicate node by comparing the value of the node with the nodes after it. If it is a duplicate, we change the next pointer of the current node so that it skips the next node and points directly to the node after the next node.

3. Code implementation

public ListNode deleteDuplicates(ListNode head) {
    
    
    ListNode p = head;
    while (p != null && p.next != null) {
    
    
        if (p.next.val == p.val) {
    
    
            p.next = p.next.next;
        } else {
    
    
            p = p.next;
        }
    }
    return head;
}

Guess you like

Origin blog.csdn.net/weixin_48683410/article/details/114179687