Given a sorted list, deleting all duplicate elements leaves only the elements in the original linked list that are not duplicates.
Have you ever encountered this problem in a real interview? YesSample 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
label Expand
Analysis: Because it is a sort of list, so each judgment and the following is not the same as the line, the same has been the same traversal to different points
Code:
/** * Definition of ListNode * class ListNode {* Public: * int val; * ListNode *next; * ListNode (int val) {* This->val = val; * This->next = NULL; *} *} */class solution{public:/** * @param head:the first node of linked list. * @return: Head node */ListNode * deleteduplicates (ListNode *head) {//write your code here Listnod E Dummy (-1); listnode* temp = &dummy; while (head) {if (head->next) {bool same = false; while (head->next&&head->next->val==head->val) {same = true; Head = head->next; } if (!same) {temp->next = new ListNode (head->val); temp = temp->next; } head = head->next; } else { Temp->next = head; Head = head->next; }} return dummy.next; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
lintcode-Delete a repeating number in a sorted list II