问题遇到的现象和发生背景
https://leetcode-cn.com/problems/reorder-list/
问题相关代码,请勿粘贴截图
class Solution {
private:
//反转链表
ListNode* reverseList(ListNode* head){
while(head == nullptr||head->next == nullptr)
return head;
ListNode* p =reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return p;
}
//找到链表中间节点
public:
void reorderList(ListNode* head) {
ListNode* newHead = reverseList(head);
ListNode* temp1 = head;
ListNode* p1 = temp1->next;
ListNode* temp2 = newHead;
ListNode* q1 = temp2->next;
while(p1){
temp1->next = temp2;
temp2->next = p1;
temp1 = p1;
temp2 = q1;
p1 = p1->next;
q1 = q1->next;
}
ListNode* temp = head;
int length = 0;
while(temp){
temp = temp->next;
length++;
}
temp = head;
for(int i = 0;i<length/2-1;i++){
temp = temp->next;
}
temp->next = nullptr;
}
};