单链表去重

作者: 飞白非白 | 来源:发表于2018-12-04 23:27 被阅读0次
    // 移除有序链表中的重复元素,保留一个重复值
    
    /**
     * Definition for ListNode
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        /**
         * @param ListNode head is the head of the linked list
         * @return: ListNode head of linked list
         */
        public static ListNode deleteDuplicates(ListNode head) { 
            // write your code here
            if(head==null){
                return null;
            }
            ListNode list=head;
            while(list.next!=null){
                if(list.val==list.next.val){
                    if(list.next.next==null){
                        list.next=null;
                    }else{
                        ListNode node=list.next;
                        list.next=node.next;
                    }
                }else{
                    list=list.next;
                }
            }
            return head;
     
        }  
    }
    
    

    相关文章

      网友评论

        本文标题:单链表去重

        本文链接:https://www.haomeiwen.com/subject/ruybcqtx.html