zoukankan      html  css  js  c++  java
  • 82. Remove Duplicates from Sorted List II

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.

    该题意思是删除链表中的重复数字,由于链表的head也可能被删除,因此需要加一个dummy node,可以使代码更加简洁

    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head == null || head.next == null)
                return head;
            //建一个dummy node,指向链表头部
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            head = dummy;
           //当链表结点的next和next.next均不为空时循环,因为需要比较这两个结点的val是否相等
            while (head.next != null && head.next.next != null) {
                if (head.next.val == head.next.next.val) {
                   //记录下重复的值     
                    int val = head.next.val;
                   //遍历删除所有值重复的结点
                    while (head.next != null && head.next.val == val) {
                        head.next = head.next.next;
                    }            
                } else {
                    head = head.next;
                }
            }
            return dummy.next;
        }
    }
  • 相关阅读:
    171-滑动窗口问题
    170-133. 克隆图
    169-150. 逆波兰表达式求值
    windows相对路径设置与取消小工具[提效]
    Sword 38
    Sword 33
    Sword 28
    Sword 26
    Sword 12
    Sword 07
  • 原文地址:https://www.cnblogs.com/bubbleStar/p/6629209.html
Copyright © 2011-2022 走看看