题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1f581e8c0f06b21b1404c73f395f334b.png)
Leetcode 328. 奇偶链表
代码(8.10 首刷看解析)
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head || !head->next)
return head;
auto evenHead = head->next;
auto odd = head, even = head->next;
while(even && even->next) {
odd->next = even->next;
odd = odd->next;
even->next = odd->next;
even = even->next;
}
odd->next = evenHead;
return head;
}
};
func oddEvenList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
odd, even := head, head.Next
evenHead := even
for even != nil && even.Next != nil {
odd.Next = even.Next
odd = odd.Next
even.Next = odd.Next
even = even.Next
}
odd.Next = evenHead
return head
}
代码(10.13 二刷看解析)
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head || !head->next)
return head;
auto a = head, b = head->next;
auto bHead = b;
while(b && b->next) {
a->next = b->next;
a = a->next;
b->next = a->next;
b = b->next;
}
a->next = bHead;
return head;
}
};