zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    

      

  • 相关阅读:
    关于data初始化值
    switch的优化替代写法
    phpstorm安装xdebug
    如何将一个列表封装为一个树形结构
    Win10系统桌面图标距离间距变大的问题
    cnpm无法加载文件的问题
    0、springboot
    1、springboot2新建web项目
    Game游戏分析
    netty学习
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444478.html
Copyright © 2011-2022 走看看