83. Remove Duplicates from Sorted List

本文介绍了一种在链表中删除重复元素的算法,确保每个元素仅出现一次。通过遍历链表并比较当前节点与前一节点的值,实现保留唯一元素的目标。提供了详细的代码实现,包括创建链表节点和遍历过程。

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

Problem:

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

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

Analysis:

本题的是保留每一个不同的节点元素,在遍历链表的时候每次保留上一个节点的值,并进行比较。代码如下:

Code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode res = new ListNode(-1);
        ListNode p = head;
        int value = p.val;
        ListNode pre = res;
        pre.next = new ListNode(p.val);
        pre = pre.next;
        p = p.next;
        while(p != null) {
            if(value != p.val) {
                //System.out.println("[msg1]: " + value);
                ListNode temp = new ListNode(p.val);
                pre.next = temp;
                pre = pre.next;
                
                value = p.val;
                p = p.next;
            } else {
                //System.out.println("[msg2]:  " + value);
                while(p != null && value == p.val) {
                    p = p.next;
                }
                if(p != null) {
                    //System.out.println("[msg3]:  " + value);
                    value = p.val;
                    ListNode temp = new ListNode(value);
                    pre.next = temp;
                    pre = pre.next;
                    p = p.next;
                } else {
                    //System.out.println("[msg4]:  " + value);
                    if(value != pre.val) {
                        ListNode temp = new ListNode(value);
                        pre.next = temp;
                        pre = pre.next;
                    }
                }
            }
        }
        
        return res.next;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值