[leetCode][Java] Remove Duplicates from Sorted List

本文介绍两种方法来删除有序链表中的重复元素,使每个元素只出现一次。第一种方法通过将链表转换为数组,利用数组操作去重后再重建链表;第二种方法直接在链表上进行迭代并跳过重复节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

题意:

给定一个有序单链表,删除单链表中的重复元素,使每个元素只显示一次。

比如:

给定1->1->2,返回1->2.

给定1->1->2->3->3,返回1->2->3.

算法分析:

方法一:

  * 链表变数组
  * 数组去重复同题目《Remove Duplicates from Sorted Array 》一样
  * 数组变新链表

  *貌似有点麻烦~~

代码如下:

public class Solution
{
  public  ListNode deleteDuplicates(ListNode head) 
    {
		if(head==null) return head;
    	ListNode newhead= new ListNode(0);
    	ArrayList<Integer> oriinput=new ArrayList<Integer>();
		int newinput[] = null;
		int i=0;
		while(head!=null)
		{
			oriinput.add(head.val);
			head=head.next;
		}
		int oriinput2[]=new int[oriinput.size()];
		for(i=0;i<oriinput.size();i++)
			oriinput2[i]=oriinput.get(i);
		newinput=removeDuplicates(oriinput2); 
		ListNode start =newhead;
		for(i=0;i<newinput.length;i++)
		{
			newhead.next=new ListNode(newinput[i]);
			newhead=newhead.next;
		}
    	return start.next;  
    }
    public static int[] removeDuplicates(int[] nums) 
    {
		int startindex = 0;
		int endindex = 0;
		int i=0;
		
    	while(endindex<nums.length)
    	{
    		while(endindex<nums.length)
    		{
    			if(nums[startindex]==nums[endindex]) 
    				endindex++;
    			else
    			{
    				break;
    			}   
    		}
    		nums[i]= nums[startindex];
			startindex=endindex;
			i++;
    	}
    	int res[]=new int[i];
    	for(int ii=0;ii<i;ii++)
    		res[ii]=nums[ii];
    	return res;
    }
}

方法二:

当出现重复元素时,指针跳跃即可。

别人家的代码:

public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)
            return head;
 
        ListNode p = head;
 
        while( p!= null && p.next != null){
            if(p.val == p.next.val){
                p.next = p.next.next;
            }else{
                p = p.next; 
            }
        }
 
        return head;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值