LeetCode - Reorder List

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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,会出现死循环
        
               
    }
};




后来上网搜了下,大部分思路都是来回反转链表,个人认为还是我的方法更好理解简便些,不知道童鞋们有什么看法=.=

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值