365天挑战LeetCode1000题——Day 068 相交链表 删除排序链表中的重复元素
160. 相交链表
代码实现(自解)
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {set<ListNode*> a_set;while (headA) {a_set.emplace(headA);headA = headA->next;}while (headB) {if (a_set.count(headB)) return headB;headB = headB->next;}return NULL;}
};
83. 删除排序链表中的重复元素
代码实现(自解)
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* deleteDuplicates(ListNode* head) {if (!head) return nullptr;ListNode *pre = head, *nex = head->next;while (nex) {if (nex->val == pre->val) {nex = nex->next;pre->next = nex;}else {pre = nex;nex = nex->next;}}return head;}
};
82. 删除排序链表中的重复元素 II
代码实现(自解)
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* deleteDuplicates(ListNode* head) {if (!head) return nullptr;ListNode* pre = head, *nex = head->next;while (nex) {if (nex->val == pre->val) {while (nex->next && nex->next->val == nex->val) {nex = nex->next;}if (!nex->next) {if (head == pre) return nullptr;nex = head;while (nex->next != pre) nex = nex->next;nex->next = nullptr;break;}pre->val = nex->next->val;pre->next = nex->next->next;nex = pre->next;}else {pre = nex;nex = nex->next;}}return head;}
};
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!