Topic
Given a sorted linked list, delete all nodes that has 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
.
Answer
It's a bit similar to the remove duplicates from Sorted List , except that all occurrences of duplicate elements are removed. The truth is still the same, but now to point the precursor pointer to a non-repeating element, if a non-repeating element is found, then the precursor pointer to know the element, otherwise delete this element. The code is as follows:
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * Next = Null *} *} */public class Solution {public ListNode deleteduplicates (ListNode head) {if (head==null| | Head.next==null) {return head; } ListNode fakehead=new ListNode (-1); Precursor pointer fakehead.next=head; ListNode Pre=fakehead; ListNode Cur=head; while (cur!=null) {//If the head repeats while (Cur.next!=null&&pre.next.val==cur.next.val) { Cur=cur.next; } if (pre.next==cur) {pre=pre.next; Head without repetition, move pre}else{pre.next=cur.next; } Cur=cur.next; } return fakehead.next; }}//Stupid method, timeout public class solution {public ListNode deleteduplicates (ListNode head) {if (head==null| | Head.next==null) {return head; } ListNode Cur=head; while (Cur!=null&&cur.next!=null) {if (cur.val!=cur.next.val) {//determines if the head repeats ListNode pre=c Ur.next; while (Pre!=null&&pre.next!=null&&pre.val==pre.next.val) {pre.next=pre.next.next; } if (pre.next!=null) {cur.next=pre.next; When the while is exiting from Pre.next==null, leave the pre current point}}else{ListNode temp=cur.next; while (Temp!=null&&cur.val==temp.val) {temp=temp.next; } head=temp; Cur=head; }} return head; }}
---EOF---
"Leetcode" Remove duplicates from Sorted List II