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

    题意:给定一个已经排好序的链表,删除链表中的重复元素

    思路;利用pre指向前一个结点,cur指向当前结点,判断两个结点值是否相等。

    public ListNode deleteDuplicates(ListNode head) {
         //要先判断head是否为null,如果在head为null的情况下执行cur = head.next,则相当于对空指针进行操作,会报空指针异常
            if (head == null)
                return head;
            ListNode pre = head;
            ListNode cur = head.next;
            while (cur != null) {
                if (pre.val == cur.val) {
                    pre.next = cur.next;
                } 
                else {
                    pre = pre.next;
                }
                cur = cur.next;
            }
            return head;
        }

     LeetCode给出的答案在判断空指针的操作上更简洁

    public ListNode deleteDuplicates(ListNode head){
            ListNode cur = head;
            //如果head=null,则程序就不会执行后半句cur.next != null,因此不存在在head=null的前提下,取head.next的情况
            while(cur != null && cur.next != null){
                if(cur.val == cur.next.val){
                    cur.next = cur.next.next;
                }
                else{
                    cur = cur.next;
                }
            }
            return head;
        }
  • 相关阅读:
    03-java实现双向链表
    04-java实现循环链表
    02-java实现单链表
    01-java实现动态数组
    安装mpi的那些坑
    gotoblas,mpich,hpl,hpcg的安装
    centos之hadoop的安装
    公告
    AFO之后……
    Codeforces Round #599 (Div. 2)的简单题题解
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/8053448.html
Copyright © 2011-2022 走看看