zoukankan      html  css  js  c++  java
  • 082 Remove Duplicates from Sorted List II 有序的链表删除重复的结点 II

    给定一个有序的链表,删除所有有重复数字的节点,只保留原始列表中唯一的数字。
    例如:
    给定 1->2->3->3->4->4->5 ,则返回 1->2->5
    给定 1->1->1->2->3 ,则返回 2->3
    详见:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/

    Java实现:

    递归实现:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head==null||head!=null&&head.next==null){
                return head;
            }
            ListNode cur=null;
            if(head.val==head.next.val){
                cur=head.next;
                while(cur!=null&&cur.val==head.val){
                    cur=cur.next;
                }
                return deleteDuplicates(cur);
            }else{
                cur=head.next;
                head.next=deleteDuplicates(cur);
                return head;
            }
        }
    }
    

     非递归实现:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            ListNode first=new ListNode(-1);
            first.next=head;
            ListNode p=head;
            ListNode last=first;
            while(p!=null&&p.next!=null){
                if(p.val==p.next.val){
                    int val=p.val;
                    while(p!=null&&p.val==val){
                        p=p.next;
                    }
                    last.next=p;
                }else{
                    last=p;
                    p=p.next;
                }
            }
            return first.next;
        }
    }
    
  • 相关阅读:
    JS中的宽高(基础知识很重要)
    JS基础知识总结
    Spring中的JdbcTemplate使用
    Spring中集合类型属性注入
    白盒交换机公司&产品列表
    虚拟化有哪几种架构
    全虚拟化与半虚拟化
    白牌交换机现状分析zz
    SDN控制器列表
    Arista公司
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8711760.html
Copyright © 2011-2022 走看看