Topic:
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
.
Category: Linked List
Code: maintaining two pointers ptr,pre
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* Deleteduplicates (listnode*head) { A if(!head) - returnhead; - if(Head &&!head->next) the returnhead; -ListNode *newhead =NewListNode (Head->val-1); -Newhead->next =head; -ListNode *pre =Newhead; +ListNode *ptr =Newhead; - while(head) + { A if(Pre->val! = Head->val && (!head->next | | Head->val! = head->next->val)) at { -Ptr->next =head; -PTR = ptr->Next; - } -Pre =head; -Head = head->Next; in } -Ptr->next =NULL; to + returnNewhead->Next; - } the};
[LeetCode82] Remove duplicates from Sorted List II