考研数据结构

单链表去重

2018-12-04  本文已影响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;
 
    }  
}

上一篇 下一篇

猜你喜欢

热点阅读