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

    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.

    去掉链表中出现过的重复的数字,然后返回链表。

    就直接遍历一次就好了,做好标记。

    /**
     * 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 || head.next == null)
                return head;
            ListNode result = head;
            ListNode first = head;
            ListNode flag ;
            int DD = 0;
            if( head.val == head.next.val )
                DD = 1;
            int del = 0;
            while( first.next != null){
                flag = first.next;
                if( first.val == flag.val){
                    del = 1;
                }else{
                    if( del == 0 && !head.equals(first) ){
                        result.next = first;
                        result = result.next;
                    }
                    del = 0;
                }
                first = first.next;
            }
            if( del == 0){
                result.next = first;
                result = result.next;
            }
            result.next = null;
            if( DD == 1 )
                return head.next;
            else
                return head;
    
        }
    }
  • 相关阅读:
    P2639 [USACO09OCT]Bessie的体重问题Bessie's We…
    P2871 [USACO07DEC]手链Charm Bracelet
    P1983 车站分级
    P1038 神经网络
    P1991 无线通讯网
    P1546 最短网络 Agri-Net
    P1197 [JSOI2008]星球大战
    P1004 方格取数
    P1111 修复公路
    pd_ds 之 hash
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/5974387.html
Copyright © 2011-2022 走看看