题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
解答:
很简单的模拟,因为是 sorted,所以找到不重复的下一个元素即可。
/** * 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) return head; if(head->next == NULL) return head; ListNode* tmp = head; ListNode* dup = NULL; while(tmp != NULL) { if(tmp->next != NULL && tmp->val == tmp->next->val){ dup = tmp; while(dup->next != NULL && dup->next->val == dup->val) dup = dup->next; dup = dup->next; tmp->next = dup; } tmp = tmp->next; } return head; } };
时间: 2024-09-30 16:24:40