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;
        }
  • 相关阅读:
    用户场景描述
    NABCD需求分析
    课堂测试返回最大子数组2
    单元测试课堂练习
    正式版
    第二次冲刺团队进展报告七
    第二次冲刺团队进展报告六
    第二次冲刺团队进展报告五
    第二次冲刺团队进展报告四
    第二次冲刺团队进展报告三
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/8053448.html
Copyright © 2011-2022 走看看