给定一个有序的链表,删除所有有重复数字的节点,只保留原始列表中唯一的数字。
例如:
给定 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;
}
}