当前位置: 首页 > article >正文

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

一、题目

在这里插入图片描述

二、思路

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

三、代码

/**
 * 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;
    }
}
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;
    }
}

http://www.kler.cn/news/355882.html

相关文章:

  • Linux 系统上生成大文件的多种方法
  • mysql操作详解
  • Linux安装 php5.6
  • java线程池bug的一些思考
  • 如何在word里面给文字加拼音?
  • java对象拷贝
  • 【Linux】进程ID和线程ID在日志中的体现
  • CentOS7安装Gitlab服务
  • python爬虫登录校验之滑块验证、图形验证码(OCR)
  • nuScenes数据集使用的相机的外参和内参
  • Spring的起源与发展
  • (已解决)vscode使用launch.json进行debug调试报错:Couldn‘t spawn debuggee:embedded null byte
  • Unity3D中Excel表格的数据处理模块详解
  • SpringBoot驱动的智能物流管理解决方案
  • Dynamic 3D Gaussians: Tracking by Persistent Dynamic View Synthesis 阅读
  • C语言笔记(指针的进阶)
  • 软件测试学习笔记丨Pycharm运行与调试
  • HBase 切片原理 详解
  • 【CSS3】很适合个人网站首页的立体布局
  • 双机架构(Dual Machine Architecture)