Java实现删除有序链表中的重复出现的元素 -----(笔记)

Java实现删除有序链表中的重复出现的元素 -----(笔记)

public class Solution {
    
    
    /**
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
    
    
        if(head == null){
    
    
            return null;
        }
        ListNode end = new ListNode(-1);
        end.next = head;
        ListNode pre = end;
        ListNode temp = head;
        while(temp!=null && temp.next!=null){
    
    
            if(temp.val == temp.next.val){
    
    
                while(temp!=null && temp.next!=null && temp.val == temp.next.val){
    
    
                    temp = temp.next;
                } 
                pre.next = temp.next;
                temp = temp.next;
            }else{
    
    
                temp = temp.next;
                pre = pre.next;
            }
        }
        return end.next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41454682/article/details/112962380