
这个题是要求只保留出现一次得元素了
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { //空链表 if(head == nullptr || head->next == nullptr) return head; ListNode* res = new ListNode(0); //在链表前加一个表头 res->next = head; ListNode* cur = res; while(cur->next != nullptr && cur->next->next != nullptr){ //遇到相邻两个节点值相同 if(cur->next->val == cur->next->next->val){ int temp = cur->next->val; //将所有相同的都跳过 while (cur->next != NULL && cur->next->val == temp) cur->next = cur->next->next; } else cur = cur->next; } //返回时去掉表头 return res->next; } };
- 时间复杂度:O(n),其中�n为链表节点数,只有一次遍历
- 空间复杂度:O(1),只开辟了临时指针,常数级空间
该代码实现了一个C++类Solution,包含一个方法deleteDuplicates,用于删除链表中所有出现多次的元素,只保留出现一次的元素。方法首先检查空链表,然后添加一个虚拟头节点,通过遍历链表,遇到相邻相同节点时跳过,最后返回新链表的头节点。时间复杂度为O(n),空间复杂度为O(1)。
342

被折叠的 条评论
为什么被折叠?



