zoukankan      html  css  js  c++  java
  • 【Leetcode】【Medium】Reorder List

    Given a singly linked list LL0→L1→…→Ln-1→Ln,
    reorder it to: L0→LnL1→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}.

    解题思路:

    设置一个指针mid指向链表的中间结点;

    将mid之后的半个链表进行反转,反转后的链表insert;

    将insert中的结点挨个插入前半段链表中;

    代码:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     void reorderList(ListNode* head) {
    12         if (!head || !head->next || !head->next->next)
    13             return;
    14         ListNode* ctrl = head;
    15         ListNode* mid = head;
    16         ListNode* insert = NULL;
    17         
    18         while (ctrl->next && ctrl->next->next) {
    19             ctrl = ctrl->next->next;
    20             mid = mid->next;
    21         }
    22         
    23         insert = reverseList(mid->next);
    24         mid->next = NULL;
    25         ctrl = head;
    26         
    27         while (insert) {
    28             ListNode* t = ctrl->next;
    29             ctrl->next = insert;
    30             insert = insert->next;
    31             ctrl->next->next = t;
    32             ctrl = t;
    33         }
    34         
    35         return;
    36     }
    37     
    38     ListNode* reverseList(ListNode* head) {
    39         if (!head->next)
    40             return head;
    41         ListNode* cur = NULL;
    42         ListNode* next = head;
    43         ListNode* left = NULL;
    44         while (next) {
    45             left = next->next;
    46             next->next = cur;
    47             cur = next;
    48             next = left;
    49         }
    50         return cur;
    51     }
    52 };
  • 相关阅读:
    基于MongoDB.Driver的扩展
    通用查询设计思想
    API接口通讯参数规范
    lambda简单记录
    list去重精简代码版
    spring boot file上传
    fastjson过滤器简单记录
    java读取properties文件
    list循环删除单个元素
    MapReduce运行流程分析
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4513499.html
Copyright © 2011-2022 走看看