题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
if (!head) {
return head;
}
ListNode *now = head;
while (now) {
ListNode *tmp = now->next;
while (tmp && (tmp->val == now->val)) {
tmp = tmp->next;
}
now->next = tmp;
now = tmp;
}
return head;
}
};
思路:模拟。因为是有序链表,所以重复元素都在一起,遍历链表,对每个元素,往后遍历删除重复的即可。