Remove Duplicates from Sorted List - Leetcode

本文介绍了一种在有序链表中删除重复元素的方法,通过双指针技巧实现,确保每个元素仅出现一次。该方法使用两个指针进行比较和链接操作,有效地移除了重复项。

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode x = new ListNode(-1);
        ListNode cur = head;
        if(cur == null)
          return cur;
          
        ListNode pre = head.next;
        if(pre == null)
          return cur;
          
        x.next = cur;  
        int lastV=cur.val;  
        while(pre != null){
            if(pre.val == lastV){
               pre = pre.next;
               cur.next = null;
            }
            else{
                cur.next = pre;
                cur = cur.next;
                lastV = cur.val;
                pre = pre.next;
            }   
        }  
        
        return x.next;
    }
}

分析:

 题目中是链表是有序的,这样用两个指针,前面一个用于探测是否相同不,后面一个用于连接

前面的探测有两种结果:如果相同,前指针继续走下去;如果不相同,后指针的连接前指针,前指针继续走下去。

注意点:做了2个链表的题目,感觉是在原来的基础上构造链表的时候,要及时将新链表的next设置能null,防止以前的数据影响链表结构。

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值