/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if (!head || !head->next || !head->next->next) return;
ListNode *pre = nullptr;
ListNode *cur = head;
while (cur->next) {
pre = cur;
cur = pre->next;
}
cur->next = head->next;
head->next = cur;
pre->next = nullptr;
reorderList(cur->next);
}
};
思路
根据题目要求,可将问题分解为首尾两个节点串接,然后余下的链表再递归处理;
使用双指针找到最后两个节点,更改最后一个节点的指向,并把倒数第二个节点的指向赋值为空;
要点
注意初始条件,节点个数在小于2个的情况下,不必进行更改;