[LeetCode][Java] Remove Duplicates from Sorted List II

本文介绍了一种算法,用于从有序链表中删除所有重复的节点,只保留原链表中的不重复节点。通过使用前后双指针技巧,可以有效地跳过连续重复的元素。

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

题意:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

题目:

给定一个有序链表,删除所有重复的节点,剩余都是原链表中的不相同的节点元素。

比如,

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

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

算法分析:

设置前后双指针,后指针遇到重复元素就一直遍历直到重复的结尾,之后前指针指向后指针,这样就略过所有的重复元素。

AC代码:

<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution 
{
    public  ListNode deleteDuplicates( ListNode head) 
    {
        ListNode pre;
        ListNode cur;
        ListNode newhead = new ListNode(0);
        newhead.next=head;
        if(head==null||head.next==null)
        	return head;
        pre=newhead;
        cur=head;
        while(cur.next!=null)
        {
	        if(cur.next.val==cur.val)//处理头几个元素相同的例子 如1 1 1 2 3 4 
	        {
	        	while(cur.next.val==cur.val)
	        	{
		        	cur=cur.next;
		        	if(cur.next==null)//处理末尾几个元素相同的例子 1 2 3 4 5 5 5
		        		break;
	        	}
		        pre.next=cur.next;
		        //pre=pre.next;
		        cur=cur.next;
		        if(cur==null)
		        	break;
	        }
	        else//处理头几个元素不相同的例子 1 2 3 4 5
	        {
	        	pre=pre.next;
	        	cur=cur.next;
	        }

        }
    	return newhead.next;
    }
}</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值