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

    题意: 

    给出一个链表,删除所有重复的结点。

    步骤:

    (1)定义一个新的头结点,用来指向head,并将head向前移动一位。

                          1  ->   1  ->  1  ->   2  ->  3

              变为    head  ->  1  ->   1  ->  1  ->   2  ->  3

    (2)遍历各结点,每次比较两个结点,head.next和head.next.next.

            1. 如果head.next.val == head.next.next.val, 两个结点的值相等,用temp记录这个值,

                从next开始依次遍历删除每个值为temp的结点,head.next = head.next.next.

            2. 如果next和next.next的值不相等,继续向后遍历,head =head.next;

    /**
     * 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) {
            if(head == null) return null;
            
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            head = dummy;
            
            while(head.next != null && head.next.next != null){
                if(head.next.val == head.next.next.val){
                    int temp = head.next.val;
                    while(head.next != null && head.next.val == temp){
                        head.next = head.next.next;
                    }
                }else{
                    head = head.next;
                }
            }
            return dummy.next;
            
        }
    }
  • 相关阅读:
    Python(4)
    docker-数据管理(3)
    docker(2)
    docker(1)
    ansible的role(6)
    windows实用cmd命令总结
    Orcal数据类型总结
    Orcal设置默认插入数据的日期和时间
    linux常用关机和重启命令
    electron关于页面跳转 的问题
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5714807.html
Copyright © 2011-2022 走看看