题解 | 链表的奇偶重排
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <clocale>
#include <codecvt>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* oddEvenList(ListNode* head) {
// write code here
// ListNode* newHead = new ListNode(0);
ListNode* head1 = new ListNode(0);
ListNode* head2 = new ListNode(0);
ListNode* t;
ListNode* p = head;
ListNode* h1 = head1;
ListNode* h2 = head2;
int cnt = 0;
while (p) {
cnt++;
t = p->next;
if (cnt % 2 == 1) {
h1->next = p;
h1 = h1->next;
}
else {
h2->next = p;
h2 = h2->next;
}
p = t;
}
h1->next = head2->next;
h2->next = nullptr;
return head1->next;
}
};
使用两个辅助头节点分别指向奇数位置和偶数位置的节点元素
注意h2->next的置空操作:
若节点总个数为奇数个,如 1->2->3->4->5,则新链表的末尾节点为4,节点4的next指针本身不为空,若不值为空,则会引起死循环
Day4

