[LeetCode] Reorder List

Question:

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}.

思路1:将链表存入一个vector,vector的元素为ListNode*,然后从前后同时开始按一定方式进行重排换位。(因为是单链表,所以如果不用指针数组保存的话,每次都需要遍历一遍去找尾结点和尾结点的前一个结点,效率会非常低)。

思路2:把整个链表划分成2个等长的子链表,如果原链表长度为奇数,那么第一个子链表的长度多1。然后翻转第二个子链表。最后合并两个子链表。

以下是思路1的实现:

Solution (C++):

/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(!head || !head -> next ) return;

        vector<ListNode *> result;
        ListNode *cur = head;
        while (cur)
        {
            result.push_back(cur);
            cur = cur -> next;
        }
        
        int len = result.size();
        vector<ListNode *>::size_type left = 0;
        vector<ListNode *>::size_type right = len - 1;
        
        while (left < right)
        {
           result[left] -> next = result[right];
           result[right--] -> next = result[++left];
        }
        result[left] -> next = NULL;
        
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值