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
.
Problem Solving Ideas:
The key is to set a dummy as the start of the linked list. began to want to use two pointers, but has been chaotic. After reading the answer, the answer is only a pointer, the same idea. The key is to be clear.
Java Code:
PublicListNode deleteduplicates (ListNode head) {if(Head = =NULL) { return NULL; } ListNode Dummy=NewListNode (0); Dummy.next=Head; ListNode P1=dummy; while(p1.next!=NULL&& P1.next.next! =NULL) { if(P1.next.val = =p1.next.next.val) {intValue =P1.next.val; while(p1.next!=NULL&& value = =p1.next.val) {P1.next=P1.next.next; } }Else{P1=P1.next; } } returnDummy.next; }
Reference:
1. http://www.programcreek.com/2014/06/leetcode-remove-duplicates-from-sorted-list-ii-java/
Leetcode Remove duplicates from Sorted List II