Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→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}
.
这题自己想了想,用STL中的deque应该非常容易,所以我的代码如下:
思路很简单,第一次遍历,把单链表中节点依次存入双向队列。
之后,分别依次从队头或者队尾弹出节点指针,将其链接起来即可
/**
* 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) {
deque <ListNode *> temp;
ListNode *p=head;
ListNode *res=head;
ListNode *temp_node=head;
ListNode *temp_res=head;
int i=0;
if(p==NULL)
return;
while(p) //将结点指针入队
{
temp.push_back(p);
if(p->next==NULL)
break;
p=p->next;
}
while(!temp.empty())
{
if(i==0)//将第一个指针出队作为头结点
{
temp_res=temp.front();
temp.pop_front();
}
else
{
if(i%2==0) //将队头弹出
{
temp_node=temp.front();
temp.pop_front();
}
else
{
temp_node=temp.back(); //将队尾弹出
temp.pop_back();
}
temp_res->next=temp_node;
temp_res=temp_node;
}
i++;
}
temp_res->next=NULL; //将最后一个指针的next值设为null,很重要,否则返回的单链表结尾next值不为NULL,会出现死循环
}
};
后来上网搜了下,大部分思路都是来回反转链表,个人认为还是我的方法更好理解简便些,不知道童鞋们有什么看法=.=