力扣 83.删除排序链表中的重复元素

一、题目

二、思路

需要比较当前节点与前一个节点的 val 是否相同,相同则删除当前节点。(如果是比较当前节点和下一节,需要检查 cur.next 是否为空)

三、代码

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = head;
        ListNode cur = head.next;
        while (cur != null) {
            if (cur.val == pre.val) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }
}
java 复制代码
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode cur = head;
        while (cur.next != null) {
            if (cur.val == cur.next.val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return head;
    }
}
相关推荐
Codingwiz_Joy12 分钟前
Day09 -实例:拿到加密密文进行解密
算法·安全·安全性测试
float_六七41 分钟前
双指针算法
算法
BingLin-Liu1 小时前
图论之cruskal算法(克鲁斯卡尔)
数据结构·算法·图论
进取星辰1 小时前
PyTorch 深度学习实战(15):Twin Delayed DDPG (TD3) 算法
pytorch·深度学习·算法
strive-debug1 小时前
C语言之 条件编译和预处理指令
算法
Sacuki2 小时前
BP神经网络公式推导与代码实现
算法
山登绝顶我为峰 3(^v^)32 小时前
VSCode + CMake
ide·vscode·算法·计算机·编辑器
勇敢滴勇2 小时前
【C++】二叉搜索树(二叉查找树、二叉排序树)详解
开发语言·c++·算法·霍夫曼树
f狐0狸x3 小时前
【蓝桥杯每日一题】3.16
c++·算法·蓝桥杯
周Echo周3 小时前
8、STL中的map和pair使用方法
开发语言·数据结构·c++·考研·算法·leetcode·pat考试