【链表】Remove Duplicates from Sorted List II(三指针)
题目:
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
.
思路:
找到重复的项,记录下他们前面的节点,然后删除。
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var deleteDuplicates = function(head) { if(head==null||head.next==null){ return head; } var l=head,r=head.next,rpre=null; var tempHead=new ListNode(0); tempHead.next=head; var pre=tempHead; while(r!=null){ if(l.val==r.val){ while(r!=null&&r.val==l.val){ rpre=r; r=r.next; } pre.next=r; if(r==null){ return tempHead.next; }else{ l=r; r=r.next; } }else{ l=l.next; r=r.next; pre=pre.next; } } return tempHead.next; };