链表无头结点
/** * 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); } }
原文:https://www.cnblogs.com/Yshun/p/14751366.html