题目描述
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
三指针
/**
* 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 head;
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
ListNode p1 = head;
ListNode p2 = head.next;
while(p2 != null){
if(p1.val != p2.val){
cur.next = p1;
cur = cur.next;
p1=p2;
p2=p2.next;
}else{
int val = p1.val;
while(val == p1.val){
p1=p1.next;
if(p1 == null) break;
}
if(p1==null) p2=null;
else p2 = p1.next;
}
}
cur.next = p1;
return dummy.next;
}
}
递归
/**
* 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||head.next==null) return head;
if(head.val == head.next.val){
while(head!=null && head.next!=null && head.val==head.next.val){
head = head.next;
}
return deleteDuplicates(head.next);
}else{
head.next = deleteDuplicates(head.next);
return head;
}
}
}