首页 > 编程语言 > 详细

82. 删除排序链表中的重复元素 II

时间:2021-05-10 19:47:35      阅读:10      评论:0      收藏:0      [点我收藏+]

链表无头结点

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null) {
            return null;
        }
        //设置一个哑结点
        ListNode dummy = new ListNode(0,head);
        ListNode cur=dummy;
        while(cur.next!=null&&cur.next.next!=null){
            if(cur.next.val==cur.next.next.val){
                int x=cur.next.val;
                while(cur.next!=null&&cur.next.val==x){
                    cur.next=cur.next.next;
                }
            }
            else{
                cur=cur.next;
            }
        }
        return dummy.next;
    }
}

链表有头结点

package leetcode;

public class demo_82 {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null) {
            return null;
        }
        if(head.next.next==null) {
            head.printNode(head);
            return head;
        }
        ListNode l=head;
        ListNode l1=head.next;
        ListNode l2=head.next.next;
        while(l2!=null) {
            if(l1.val==l2.val) {
                while(l1.val==l2.val&&l2.next!=null) {
                    l2=l2.next;
                }
            }
            else {
                l.next=l1;
                l=l.next;
            }
            if(l2.next!=null) {
                l1=l2;
                l2=l2.next;
            }
            else {
                if(l1.val!=l2.val) {                    
                    l.next=l2;
                    l=l.next;
                }
                l2=l2.next;
            }
        }
        //终止单链表
        l.next=null;
        head.printNode(head);
        return head;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] str= {1,1,2,3,3,4,4,5,6,6};
        ListNode head=new ListNode();
        head.creatnode(head, str);
        demo_82 d82=new demo_82();
        d82.deleteDuplicates(head);
    }

}

 

82. 删除排序链表中的重复元素 II

原文:https://www.cnblogs.com/Yshun/p/14751366.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!