zoukankan      html  css  js  c++  java
  • [LeetCode] 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}.

    思路:找到中间节点,将链表的后半部分就地逆置。然后插入到前半部分。

       时间复杂度O(n),空间复杂度O(1) 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 == NULL || head->next == NULL || head->next->next == NULL) 
    13             return;
    14         
    15         int length = 0;
    16         for (ListNode *pter = head; pter != NULL; pter = pter->next) {
    17             ++length;
    18         }
    19         
    20         int half_length = 1;
    21         ListNode *half = head;
    22         while (half_length < (length / 2)) {
    23             ++half_length;
    24             half = half->next;
    25         }
    26         
    27        //reverse
    28        ListNode *pter = half->next;
    29        half->next = NULL;
    30        while (pter != NULL) {
    31            ListNode *next_node = pter->next;
    32            pter->next = half->next;
    33            half->next = pter;
    34            pter = next_node;
    35        }
    36       
    37 ListNode *pter2 = head; 38 pter = half->next; 39 while (pter2 != half) { 40 ListNode *next_node = pter->next; 41 half->next =next_node; 42 pter->next = pter2->next; 43 pter2->next = pter; 44 pter2 = pter2->next->next; 45 pter = next_node; 46 } 47 } 48 };
  • 相关阅读:
    VPS服务器 基本配置
    WCF 系列 → HelloWord
    ASP.NET MVC3 常用整理
    ASP.NET MVC3 过滤器 Filter
    NVelocity系列 → NVelocity配置详解
    网站安全检测 Web 安全测试工具
    ASP.NET MVC3.0 静态化实现
    CSS3的动画泡沫按钮
    SQL 大数据优化
    用友备份失败,超时己过期
  • 原文地址:https://www.cnblogs.com/vincently/p/4073442.html
Copyright © 2011-2022 走看看