题解 | #删除有序链表中重复的元素-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) { // write code here if (!head) return head; auto cur = head; while (cur && cur->next) { if (cur->val == cur->next->val) cur->next = cur->next->next; else cur = cur->next; } return head; } };
- 思路:双指针,cur 和 cur->next 两个指针去重
- 当不是尾节点时,判断当前节点的值与当前节点next的值是否相等,如果相等,则next指针后移一位(即删除next节点);否则跳到next指针的位置。
- 时间复杂度:O(n)
- 空间复杂度:O(1)