当前位置: 代码迷 >> 综合 >> leetcode-83 Remove Duplicates from Sorted List
  详细解决方案

leetcode-83 Remove Duplicates from Sorted List

热度:76   发布时间:2023-12-16 05:34:44.0

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

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

Example 2:

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

 

去除重复的数据:

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

  相关解决方案