Leetcode ReorderList

时间:2022-07-04 22:34:07
Leetcode ReorderList

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

(1)找出中间节点

(2)将后部分节点反转

(3)将前部分节点和后部分节点合并

#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <list> using namespace std; struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x), next(NULL){}
}; void printList(ListNode* head){
while(head!=NULL){
cout<<"->"<<head->val;
head = head->next;
}
cout<<endl;
} ListNode* reverse(ListNode *head){
ListNode *pre = head;
ListNode *p = head->next;
head->next =NULL;
while(p!=NULL){
ListNode* tmp = p->next;
p->next = pre;
pre = p;
p = tmp;
}
return pre;
} ListNode* merge(ListNode *head1, ListNode *head2){
ListNode* p = head1;
while(head2!=NULL){
ListNode *tmp = head2->next;
head2->next = p->next;
p->next = head2;
p = p->next->next;
head2 = tmp;
}
return head1; } void reorderList(ListNode *head){
if(head == NULL || head->next == NULL) return;
ListNode *slow = head,*fast = head;
while(fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
}
ListNode *head2 = slow->next;
slow->next = NULL;
ListNode *head1 = head;
//printList(head2);
head2 = reverse(head2);
//printList(head2);
head = merge(head1,head2);
} int main(){
ListNode *head= new ListNode();
ListNode *p = head;
for(int i =; i <= ; ++ i){
ListNode *a= new ListNode(i);
p->next = a;
p = a;
}
reorderList(head);
printList(head);
}