题解 | #链表的奇偶重排#
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (head == nullptr || head->next == nullptr || head->next->next == nullptr) {
return head;
}
ListNode* oddListHead = new ListNode(head->val);
ListNode* oddList = oddListHead;
ListNode* evenListHead = new ListNode(head->next->val);
ListNode* evenList = evenListHead;
auto p = head;
while (p->next != nullptr && p->next->next != nullptr) {
p = p->next->next;
auto q = new ListNode(p->val);
oddList->next = q;
oddList = q;
}
p = head->next;
while (p->next != nullptr && p->next->next != nullptr) {
p = p->next->next;
auto q = new ListNode(p->val);
evenList->next = q;
evenList = q;
}
oddList->next = evenListHead;
return oddListHead;
}
};
查看17道真题和解析
360集团公司福利 395人发布