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;
        }
    }
  • 相关阅读:
    Rotate List
    Spiral Matrix II
    Jump Game
    Maximum Subarray
    Pow(x, n)
    Anagrams
    Permutations
    unity 相机的问题
    NGUI 学习
    空间数据库1
  • 原文地址:https://www.cnblogs.com/bubbleStar/p/6629209.html
Copyright © 2011-2022 走看看