zoukankan      html  css  js  c++  java
  • [leedcode 83] 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; }
     * }
     */
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            //两种解法:
            //一种声明三个节点,一个代表index之前的均满足要求,first是遍历的节点,pre是first的前置,便于删除节点时保留前置
            //一种是只需要一个节点,该节点和其后置值进行比较,如果相等,直接删除,如果不等指向下一节点
            if(head==null||head.next==null) return head;
          /*  ListNode pre=head;
            ListNode first=head.next;
            ListNode index=head;
            while(first!=null){
                if(index.val==first.val){
                    pre.next=first.next;
                    first=first.next;
                }else{
                    pre=first;
                    first=first.next;
                    index=index.next;
                }
            }
            return head;*/
            ListNode pre=head;
            while(pre.next!=null){
                if(pre.next.val==pre.val){
                    pre.next=pre.next.next;
                }else{
                    pre=pre.next;
                }
            }
            return head;
        }
    }
  • 相关阅读:
    AI CV 会议2018
    ubuntu 更改默认亮度
    ubuntu安装latex
    过滤文件代码 python
    ubuntu安装pycharm桌面快捷方式
    Ubuntu 14.04 鼠标消失解决方案
    ffmpeg常用命令
    FFMPEG 在ubuntu下的安装与使用
    pragma once
    chrono--高精度计时
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4647943.html
Copyright © 2011-2022 走看看