给定一个单链表L: L0→L1→…→Ln-1→Ln,
重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…
必须在不改变节点值的情况下进行原地操作。
样例
样例 1:
输入: 1->2->3->4->null
输出: 1->4->2->3->null
样例 2:
输入: 1->2->3->4->5->null
输出: 1->5->2->4->3->null
挑战
你能在不改变节点值的情况下原地完成吗?
栈和队列解法
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The head of linked list.
* @return: nothing
*/
void reorderList(ListNode * head) {
// write your code here
if(head==NULL||head->next==NULL) return;
ListNode*p=head->next;
stack<ListNode*> tmp1;
queue<ListNode*>tmp2;
while(p)
{
tmp1.push(p);
tmp2.push(p);
p=p->next;
}
p=head;
int count=1;
while(!tmp1.empty()&&!tmp2.empty()&&tmp1.top()!=tmp2.front())
{
if(count%2)
{
p->next=tmp1.top();
p=p->next;
tmp1.pop();
}
else
{
p->next=tmp2.front();
p=p->next;
tmp2.pop();
}
count++;
}
p->next=tmp1.top();
p=p->next;
p->next=NULL;
}
};
vector:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The head of linked list.
* @return: nothing
*/
void reorderList(ListNode * head) {
// write your code here
if(head==NULL||head->next==NULL) return;
ListNode*p=head;
vector<ListNode*>tmp;
while(p)
{
tmp.push_back(p);
p=p->next;
}
int front=0;
int back=tmp.size()-1;
while(front<back)
{
tmp[front]->next=tmp[back];
tmp[back--]->next=tmp[++front];
}
tmp[front]->next=NULL;
}
};