题解 | #删除有序链表中重复的元素-II#

删除有序链表中重复的元素-II

https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        // write code here
        if(head==null){
            return null;
        }
	  //保存去重后的集合
        ArrayList<Integer> quchong=new ArrayList<>();
	  //保存重复元素的集合
        ArrayList<Integer> chongfu=new ArrayList<>();
	  //保存不包括重复元素的集合
        ArrayList<Integer> list=new ArrayList<>();
        ListNode getQuChong=head;
	  //分别添加到指定集合
        while(getQuChong!=null){
            if(quchong.contains(getQuChong.val)){
                chongfu.add(getQuChong.val);
                getQuChong=getQuChong.next;
            }else{
                quchong.add(getQuChong.val);
                getQuChong=getQuChong.next;
            }
        }
	  //添加到不包括重复的集合
        for(Integer num:quchong){
            if(!chongfu.contains(num)){
                list.add(num);
            }
        }
	  //如果为空,说明初始值一样
        if(list.isEmpty()){
            return null;
        }
	  //生成链表
        int i=1;
        Integer first=list.get(0);
        ListNode tmp=new ListNode(first);
        ListNode returnList=tmp;
        for(Integer num:list){
            if(i==1){
                i++;
                continue;
            }
            ListNode tmpNode=new ListNode(num);
            tmp.next=tmpNode;
            tmp=tmp.next;
        }
        return returnList;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务