方法一:基本方法
将链表分为两半,翻转后一半,再将两个链表合并。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* cutlist(ListNode* head){ //分割链表,返回后一半首地址
if(!head || !head->next)
return NULL;
ListNode* slow=head;
ListNode* fast=head->next;
while(fast!=NULL && fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
ListNode* p=slow->next;
slow->next=NULL;
return p;
}
ListNode* reverseList(ListNode* head) { //翻转链表
if(!head)
return NULL;
ListNode* p=NULL,*q=head;
while(q){
ListNode* tmp=q->next;
q->next=p;
p=q;
q=tmp;
}
return p;
}
public:
void reorderList(ListNode* head) {
ListNode* tail=cutlist(head);
tail=reverseList(tail);
ListNode* p=head;
while(tail){
ListNode* q=tail->next;
tail->next=p->next;
p->next=tail;
tail=q;
p=p->next->next;
}
}
};
方法二:转化为数组
class Solution {
public:
void reorderList(ListNode* head) {
if(!head)
return;
vector<ListNode*> arr;
while(head){
arr.push_back(head);
head=head->next;
}
int i=0,j=arr.size()-1;
while(i<j){
arr[i]->next=arr[j];
i++;
if(i==j)
break;
arr[j]->next=arr[i];
j--;
}
arr[i]->next=NULL;
}
};