Given a singly linked list L: L0→L1→…→Ln-1→Ln,
rearrange it into: L0→Ln→L1→Ln-1→L2→Ln-2→…
You can't just change the value inside the node, but need to actually exchange the node.
Example 1:
Given a linked list 1->2->3->4, rearrange to 1->4->2->3.
Example 2:
Given a linked list 1->2->3->4->5, rearrange it to 1->5->2->4->3.
Problem-solving idea:
a time-consuming and memory-intensive method, but especially easy to understand, recursion! 1->2->3->4, first 1 points to 4, and breaks the pointer of 3 to 4, and then 4 points back to the next of 1, which is 2. At this time, it is traversed in the set of 2->3. Since the linked list whose length is shorter than 3 can be returned directly, the return code is as follows:
/**
* 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) {
exchange(head);
}
void exchange(ListNode * node){
// 计算长度,如果长度小于等于2,说明到最中间了,返回
int len = 0;
ListNode * temp = node;
while(temp != nullptr){
temp = temp -> next;
len ++;
if(len > 2){
break;
}
}
if(len <= 2){
return;
}
// 双指针一个用于遍历,一个用于指向下一个节点
ListNode * temp1 = node -> next;
ListNode * temp2 = node;
//一直遍历到倒数第二个指针
while(temp2 -> next -> next != nullptr){
temp2 = temp2 -> next;
}
ListNode * temp3 = temp2;
ListNode * temp4 = temp2 -> next;
// 断开与最后一个节点的连接
temp3 -> next = nullptr;
node -> next = temp4;
temp4 -> next = temp1;
// 进行下一次交换
exchange(temp4 -> next);
}
};
/*作者:heroding
链接:https://leetcode-cn.com/problems/reorder-list/solution/fei-chang-rong-yi-li-jie-de-si-lu-by-heroding/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/