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

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

https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79

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
	  //头节点为空返回NULL
        if(head==null){
            return null;
        }
	  //使用List的特新:有序来通过contains方法去重
        ArrayList<Integer> list=new ArrayList<>();
        ListNode getList=head;
        while(getList!=null){
		  //如果包含该元素则不放入集合
            if(!list.contains(getList.val)){
                list.add(getList.val);
            }
            getList=getList.next;
        }
	  //生成链表
        Integer first=list.get(0);
        ListNode tmp=new ListNode(first);
        ListNode returnList=tmp;
        int i=1;
        for(Integer num:list){
            if(i==1){
                i++;
                continue;
            }
            ListNode tmpNode=new ListNode(num);
            tmp.next=tmpNode;
            tmp=tmp.next;
        }
        return returnList;
    }
}

全部评论

相关推荐

头像
2024-12-19 18:11
英特尔_Software_engineer
下水道鼠鼠鼠鼠:男的能去当技师吗 好进吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务