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
.
链表去重问题,用三个指针和flag来判断是否指向了重复值
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null)return head;
ListNode p = new ListNode(0);
p.next = head;
ListNode pre = p;
ListNode cur = p.next;
ListNode aft = p.next.next;
boolean f = false;
while(aft!=null){
if(cur.val==aft.val){
f = true;
cur = aft;
aft = aft.next;
if(aft==null)pre.next = null;
}
else if(f){
pre.next = aft;
cur = aft;
aft = aft.next;
f = false;
}
else{
pre.next = cur;
pre = pre.next;
cur = aft;
aft = aft.next;
}
}
return p.next;
}
}