Remove duplicates from Sorted List II
Problem:
Given a sorted linked list, delete all nodes that has duplicate numbers, leaving only distinct numbers from the Original list.
Ideas:
Prepre Pre cur hands interaction
My Code:
Public classSolution { PublicListNode deleteduplicates (ListNode head) {if(Head = =NULL|| Head.next = =NULL)returnHead; ListNode Dummy=NewListNode (-1); Dummy.next=Head; ListNode Prepre=dummy; ListNode Pre=Head; ListNode cur=Head.next; while(cur! =NULL) { if(Cur.val = =pre.val) { while(cur! =NULL&& Cur.val = =pre.val) {cur=Cur.next; } Prepre.next=cur; Pre=cur; if(cur! =NULL) cur=Cur.next; Elsecur=NULL; } Else{Prepre=Pre; Pre=cur; Cur=Cur.next; } } returnDummy.next; }}
View Code
The Learning Place:
- This problem is nothing more than using two pointers to mark the front and back position or three pointers, mark the position before and after the relationship, then draw the picture is almost.
- Of course, others can also be done by not using the logo position before and after the relationship, such as remove duplicates from Sorted List, someone wrote such a concise code, by moving or not moving method, concise and clear.
Public classSolution { PublicListNode deleteduplicates (ListNode head) {if(Head = =NULL) { return NULL; } listnode Node=Head; while(Node.next! =NULL) { if(Node.val = =node.next.val) {Node.next=Node.next.next; } Else{node=Node.next; } } returnHead; }}
View Code
Remove duplicates from Sorted List II