• Reorder List -- leetcode


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


    基本思路:

    先找到中间结点。

    然后将后半部分链表进行反转;

    再合并这两个链表。


    在leetcode上实际运行时间为72ms。


    /**
     * 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 || !head->next)
                return;
                
            ListNode *walker = head;
            ListNode *runner = head->next;
            while (runner && runner->next) {
                walker = walker->next;
                runner = runner->next;
                runner = runner->next;
            }
            
            ListNode middle(0);
            runner = walker;
            walker = walker->next;
            runner->next = NULL;
            while (walker) {
                ListNode *bak = walker->next;
                walker->next = middle.next;
                middle.next = walker;
                walker = bak;
            }
            
            while (middle.next) {
                ListNode *bak = middle.next->next;
                middle.next->next = head->next;
                head->next = middle.next;
                head = head->next->next;
                middle.next = bak;
            }
        }
    };


    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    input光标位置
    清除浮动
    CSS的两种盒模型
    网页中常用的命名
    清除inline-block元素默认间距
    自定义复选框样式及全选操作
    如何用elementui去实现图片上传和表单提交,用axios的post方法
    datatables
    9273:PKU2506Tiling
    666:放苹果
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4872909.html
Copyright © 2020-2023  润新知