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
.
Topic: Given an ordered single-linked list, delete all duplicate elements, only one occurrence.
Problem-solving ideas: Record the precursor node, if the current element is duplicated, directly to the predecessor node next point, the loop can be. The code is still very tangled. WA took five or six times.
PublicListNode deleteduplicates (ListNode head) {if(head==NULL|| head.next==NULL){ returnHead; } ListNode Dummy=NewListNode (0); ListNode ptr=Head; while(head!=NULL) {ptr=Head; while(ptr.next!=NULL&&ptr.val==ptr.next.val) {ptr=Ptr.next; } if(head!=ptr) {Head=Ptr.next; }Else{ Break; }} Dummy.next=Head; ListNode tmp=Head; while(tmp!=NULL) {ptr=Tmp.next; if(ptr==NULL){ Break; } while(ptr!=NULL&&ptr.next!=NULL&&ptr.val==ptr.next.val) {ptr=Ptr.next; } if(ptr==Tmp.next) {tmp=Tmp.next; Continue; } Tmp.next=Ptr.next; } returnDummy.next; }
Remove duplicates from Sorted List Ii--leetcode