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;
        }
    }
    
  • 相关阅读:
    05_XML的解析_01_dom4j 解析
    04_SSM框架整合(Spring+SpringMVC+MyBatis)
    03_入门程序(注解方式,掌握)
    02_入门程序(非注解方式,了解)
    01_SpringMVC流程架构图
    21_resultMap和resultType总结
    20_高级映射:多对多查询
    inline函数的总结
    【C++】C++函数重载的总结
    优先队列
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8711760.html
Copyright © 2011-2022 走看看