zoukankan      html  css  js  c++  java
  • leetcode

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

    个人思路:

    1,找到链表的中点,断开分为两部分,对链表的后半部分进行反转,然后再合并这两部分链表即可

    代码:

     1 #include <stddef.h>
     2 
     3 struct ListNode
     4 {
     5     int val;
     6     ListNode *next;
     7     ListNode(int x) : val(x), next(NULL) {}
     8 };
     9 
    10 class Solution {
    11 public:
    12     void reorderList(ListNode *head) {
    13         if (!head || !head->next)
    14         {
    15             return;
    16         }
    17 
    18         int length = 0;
    19         ListNode *current = head;
    20 
    21         while (current)
    22         {
    23             current = current->next;
    24             ++length;
    25         }
    26 
    27         ListNode *firstHead = head;
    28         int firstLength = length / 2 + length % 2;
    29         ListNode *secondHead = NULL;
    30         current = firstHead;
    31 
    32         for (int i = 0; i < firstLength; ++i)
    33         {
    34             current = current->next;
    35         }
    36         secondHead = current;
    37 
    38         //对second链表进行反转
    39         ListNode dummy(-1);
    40         dummy.next = secondHead;
    41         ListNode *pre = secondHead;
    42         current = secondHead->next;
    43 
    44         while (current)
    45         {
    46             pre->next = current->next;
    47             current->next = dummy.next;
    48             dummy.next = current;
    49             current = pre->next;
    50         }
    51 
    52         //合并first链表和second链表
    53         ListNode *firstCur = firstHead;
    54         ListNode *secondCur = dummy.next;
    55         ListNode *temp = NULL;
    56 
    57         while (firstCur && secondCur)
    58         {
    59             temp = secondCur->next;
    60             secondCur->next = firstCur->next;
    61             firstCur->next = secondCur;
    62 
    63             firstCur = secondCur->next;
    64             secondCur = temp;
    65         }
    66 
    67         if (firstCur)
    68         {
    69             firstCur->next = NULL;
    70         }
    71     }
    72 };
    View Code
  • 相关阅读:
    ubuntun16.04不支持intel的最新网卡,升级到17.10后解决
    python网络爬虫之使用scrapy下载文件
    Django之QuerySet 创建对象
    一起来学linux:磁盘与文件系统:
    python自动化运维九:Playbook
    一起来学linux:FTP服务器搭建
    Learning Scrapy 中文版翻译 第二章
    python自动化运维八:Ansible
    linux c编程:make编译一
    【原创】大叔经验分享(27)linux服务器升级glibc故障恢复
  • 原文地址:https://www.cnblogs.com/laihaiteng/p/3959266.html
Copyright © 2011-2022 走看看