题目出处:https://leetcode-cn.com/problems/odd-even-linked-list/
思路:1. 第一次遍历,用哈希表记录第i个节点和i+2节点的映射。
2. 一个指针指向第一个节点(奇数节点),一个指针指向第二个节点(偶数节点),分别根据哈希映射找到下一个节点,将其连接。
3. 最后将两个链表相连 。
/**
* 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* oddEvenList(ListNode* head) {
if(!head || !head->next){
return head;
}
ListNode* odd = head;
ListNode* even = head->next;
ListNode* second_head = even;
unordered_map<ListNode*, ListNode*> mp;
ListNode* cur = head;
while(cur && cur->next){
mp[cur] = cur->next->next;
cur = cur->next;
}
while(odd){
odd->next = mp[odd];
if(odd->next == nullptr){
break;
}
odd = odd->next;
}
while(even){
even->next = mp[even];
if(even->next == nullptr){
break;
}
even = even->next;
}
odd->next = second_head;
return head;
}
};