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.
The idea of solving a problem is to set a flag that contains duplicate elements, and then use a double pointer, one to shift, and one to store.
/** * 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) {ListNode p = head;
ListNode dummy = new ListNode (0);
ListNode q = dummy;
Boolean flag = false;
while (P! = null) {flag = false;
while (P.next! = null && P.val = = p.next.val) {p = p.next;
Flag = true;
} if (!flag) {q.next = P;
Q = q.next;
} p = P.next;
} q.next = null;
return dummy.next; }
}