Remove Duplicates from Sorted List II

来源:互联网 发布:php商城项目描述 编辑:程序博客网 时间:2024/06/04 08:49

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.

与上一题的区别是删除重复元素,同时重复的元素不止两个。

public ListNode deleteDuplicates(ListNode head) {if(head==null||head.next==null)return head;ListNode ll=new ListNode(0);ll.next=head;ListNode newHead=ll;while(ll.next!=null&&ll.next.next!=null){if(ll.next.val==ll.next.next.val){int t=ll.next.val;while(ll.next!=null&&ll.next.val==t)ll.next=ll.next.next;}elsell=ll.next;}return newHead.next;}

0 0
原创粉丝点击