deleteDuplicates- delete duplicate elements in the sorted linked list

Title description

Given a sorted linked list, delete all duplicate elements so that each element appears only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

Problem-solving ideas

1. Make a note of two variables l (fixed) and r (moving to the right)
2. Sorting problem encountered repeated numbers-turning numbers encountered (- different from the previous number or does not meet any conditions)
3. l refers to r , L is fixed to r again, and r continues to repeat 2
4. When finally l and r point to the same type of numbers, that is to say, there is no turning number afterwards (special processing, reference code)

Code demo

class Solution {
    
    
    public ListNode deleteDuplicates(ListNode head) {
    
    
        if(head==null)
            return head;
     ListNode l=head;
     ListNode r=l.next;
     while (r!=null)
        {
    
    
            if(r.val>l.val)
            {
    
    
                l.next=r;
                l=r;
            }
            r=r.next;
        }
     if(l.next!=null&&l.val==l.next.val)
         l.next=null;
     return head;
    }
}

effect

info
		解答成功:
		执行耗时:0 ms,击败了100.00% 的Java用户
		内存消耗:37.8 MB,击败了67.72% 的Java用户

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/113277571