Topic
Given a sorted list, deleting all duplicate elements leaves only the elements in the original linked list that are not duplicates.
Sample Example
Give 1->2->3->3->4->4->5->null, return 1->2->5->null
Give 1->1->1->2->3->null, return 2->3->null
Solving
Record the same number
One of the same save, multiple skipped
/** * Definition for ListNode * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; * } * } */ Public class solution { /** * @param ListNode Head is the head of the linked list * @return: ListNode head of the LI nked list * / Public StaticListNodedeleteduplicates(ListNode head) {//Write your code hereListNode Newhead =NewListNode (0);if(Head = =NULL|| Head.next = =NULL)returnHead ListNode cur = newhead; ListNode prev = head; while(head!=NULL) {ListNode p = head;intCount =0;//Record the number of identical nodes while(p!=NULL&& P.val = = head.val) {p = p.next; count++; }if(count==1){//1 instructions on oneCur.next = head; cur = cur.next; head = Head.next; }Elsehead = p; } Cur.next =NULL;//Disconnect the back node returnNewhead.next; }}
Delete duplicate numbers in a sorted list II