题目:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
代码:
方法一——使用map:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if (!head)return;
map<int, ListNode*> m;
ListNode* p = head;
int i = 0;
while (p) {
m[i] = p;
p = p->next;
i++;
}
int len = m.size();
i = 0;
for ( ;i < len/2; i++) {
m[len - 1 - i]->next = m[i]->next;
m[i]->next = m[len - i - 1];
}
m[i]->next = NULL;
head = m[0];
}
};
方法二——快慢指针、反转链表、合并:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode *head)
{
if(head==NULL||head->next==NULL)
return;
//分成两段
ListNode *preSlow=NULL;
ListNode *slow=head,*fast=head;
while(fast&&fast->next)
{
preSlow=slow;
slow=slow->next;
fast=fast->next->next;
}
preSlow->next=NULL; //前半段
//反转后半段
ListNode *newBeg=slow;
ListNode *last=newBeg->next;
while(last)
{
ListNode *temp=last->next;
last->next=newBeg;
newBeg=last;
last=temp;
}
slow->next=NULL;
//合并
fast=head;
preSlow=NULL;
while(fast) //注:以前半段为条件
{
ListNode *tem=newBeg->next;
newBeg->next=fast->next;
fast->next=newBeg;
fast=newBeg->next;
preSlow=newBeg;
newBeg=tem;
}
if(newBeg !=NULL) //因节点个数为奇数时,后段比前段多一个,所以最后要判断
preSlow->next=newBeg;
}
};
想法:
多看看别人的方法