Given a sorted linked list, delete all nodes that have 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
.
Subscribe to see which companies asked this question
解法1:一个简单的想法是使用map<int,int>来保存链表中每个不同元素出现的次数,然后遍历map,只要key对应的val不为1,则删除链表中所有值为key的节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { map<int, int> m; ListNode* curr = head; while (curr != NULL) { ++m[curr->val]; curr = curr->next; } ListNode* help = new ListNode(0); help->next = head; curr = help; map<int, int>::iterator iter = m.begin(); for (; iter != m.end(); ++iter) { if (iter->second != 1) { while (curr->next != NULL && curr->next->val != iter->first) curr = curr->next; for (int i = 0; i < iter->second; ++i) { ListNode* del = curr->next; curr->next = curr->next->next; delete del; } } } return help->next; } };
解法2:可以降低空间复杂度为O(1)。如果找到相邻的两个节点值一样,则同时删除这两个节点,并且记录下这个值,如果接下来的节点还是这个值也删除即可。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* help = new ListNode(0); help->next = head; ListNode *first = help, *second = head, *third = head->next; while (third != NULL) { if (second->val == third->val) { int dupVal = second->val; while (second != NULL && second->val == dupVal) { ListNode* del = second; first->next = second->next; second = second->next; delete del; } if (second == NULL) break; third = second->next; } else { first = second; second = third; third = third->next; } } return help->next; } };