LeetCode | Odd Even Linked List
https://leetcode.com/problems/odd-even-linked-list/
建两个dummy node,一个维护奇数节点构成的链表,另一个维护偶数节点构成的链表,最后再拼接起来。注意偶数节点构成的链表最后一个节点的next
域要置空,否则可能会导致出现环路。
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (!head || !head->next) return head;
ListNode dummy_odd(0), dummy_even(0);
ListNode *p1 = &dummy_odd, *p2 = &dummy_even;
bool is_odd = true;
while (head) {
if (is_odd) { p1->next = head; p1 = p1->next;}
else { p2->next = head; p2 = p2->next; }
head = head->next;
is_odd = !is_odd;
}
p1->next = dummy_even.next;
p2->next = NULL; // very important
return dummy_odd.next;
}
};