题解 | #重排链表#
重排链表
https://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseList(ListNode *head) {
if (!head || !head->next) {
return head;
}
ListNode *res = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return res;
}
void reorderList(ListNode *head) {
if (!head || !head->next) {
return;
}
ListNode *fast = head;
ListNode *slow = head;
ListNode *bef = nullptr;
while (fast && fast->next) {
fast = fast->next->next;
bef = slow;
slow = slow->next;
}
bef->next = nullptr;
slow = reverseList(slow);
ListNode *res = nullptr;
ListNode **pt = &res;
while (head) {
*pt = head;
head = head->next;
pt = &((*pt)->next);
*pt = slow;
slow = slow->next;
pt = &((*pt)->next);
}
if (slow) {
*pt = slow;
slow = slow->next;
pt = &((*pt)->next);
}
head = res;
}
};
思路:先分成两个链表,一个从前往后,一个从后往前(反转链表),然后再一个个节点合成即可。
链表结点个数可能为奇数个,所以最后反转链表可能多出来一个,特殊处理。
查看16道真题和解析
