• LeetCode | Remove Duplicates from Sorted List


    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.

    /**
     * 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) {
            if (head==null || head.next==null) return head;
            
            ListNode pre = head;
            ListNode cur = head.next;       //cur与pre用来在list中找重复
            ListNode non_dup_end = head;    //用来标记无重复list的最后一个节点
            
            while(cur != null){
                if (pre.val != cur.val){    //如果不是重复的话,属正常态,就把non_dup_end向后移一位,然后把cur.val赋过去
                    non_dup_end = non_dup_end.next;
                    non_dup_end.val = cur.val;
                }
                cur = cur.next;            //如果是重复的话,本次循环什么都不做,直到找到后边第一个不再重复的元素值赋给non_dup_end
                pre = pre.next;
            }
            non_dup_end.next = null;       //不同于数组,循环之后要记得把无重复list后边多余的节点删掉
            return head;
        }
    }
    

      

  • 相关阅读:
    Linux查看物理CPU个数、核数、逻辑CPU个数
    shell脚本中格式化日期
    MySQL中常用字符串函数
    Xtrabackup 使用方法
    LinuxShell算术运算
    mysql高可用方案MHA介绍
    CentOS安装scp命令
    源码编译安装MySQL
    mysql编译参数详解(./configure)
    SparkStreaming 结合Kafka 时丢数据
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444478.html
Copyright © 2020-2023  润新知