328. Odd Even Linked List**
https://leetcode.com/problems/odd-even-linked-list/
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O ( 1 ) O(1) O(1) space complexity and O ( n o d e s ) O(nodes) O(nodes) time complexity.
Example 1:
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL
Example 2:
Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULL
Note:
- The relative order inside both the even and odd groups should remain as it was in the input.
- The first node is considered odd, the second node even and so on …
C++ 实现 1
关于奇偶的位置进行划分而不是节点的值. 思路, 使用两个节点 odd
以及 even
, 分别挂载位置为奇以及位置为偶的节点, 最后将 even
链表挂载到 odd
后面.
使用 isOdd
判断当前节点时奇节点还是偶节点. 另外注意最后要设置 q->next = nullptr
.
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (!head) return nullptr;
ListNode *odd = new ListNode(0), *even = new ListNode(0);
auto p = odd, q = even;
bool isOdd = true;
while (head) {
if (isOdd) {
p->next = head;
p = p->next;
}
else {
q->next = head;
q = q->next;
}
head = head->next;
isOdd = !isOdd;
}
q->next = nullptr; // 这一步不要忘了
p->next = even->next;
return odd->next;
}
};
C++ 实现 2
两年前的代码. 参考 https://leetcode.com/problems/odd-even-linked-list/solution/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (!head || !head->next)
return head;
ListNode *odd = head, *even = head->next, *evenHead = even;
// 这里没有设置虚拟头结点, 而是使用 head 来表示奇节点链表的头节点,
// evenHead 表示偶节点链表的头结点, 可以看到, 判断偶节点 even 以及
// next 是否存在让代码清晰很多.
while (even && even->next) {
odd->next = even->next;
odd = odd->next;
even->next = odd->next;
even = even->next;
}
odd->next = evenHead;
return head;
}
};