zoukankan      html  css  js  c++  java
  • Reorder List

    先将链表用快慢指针分成两部分,再将后一半进行倒置,倒置后再合并。

     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  
    10  ListNode* reverse(ListNode *head)
    11 {
    12     if(head==NULL||head->next==NULL)return head;
    13     ListNode prehead(0),*p;
    14     prehead.next=head;
    15     while(head->next)
    16     {
    17         p=head->next;
    18         head->next=p->next;
    19         p->next=prehead.next;
    20         prehead.next=p;
    21     }
    22     
    23     return prehead.next;
    24 }
    25 
    26 class Solution {
    27 public:
    28     ListNode *reorderList(ListNode* head) {
    29       if(head==NULL||head->next==NULL)return head;
    30       ListNode prehead(0),*slower,*fast,*start;
    31       prehead.next=head;
    32       slower=fast=head;
    33       while(fast&&fast->next)
    34       {
    35           slower=slower->next;
    36           fast=fast->next->next;
    37       }
    38       start=slower->next;
    39       slower->next=NULL;
    40      start=reverse(start);
    41      while(head&&start)
    42      {
    43         fast=start->next;
    44         start->next=head->next;
    45         head->next=start;
    46         
    47         head=head->next->next;
    48         start=fast;
    49      }
    50      
    51      return prehead.next; 
    52       
    53         
    54     }
    55 };
  • 相关阅读:
    【转】java线程池ThreadPoolExecutor使用介绍
    java的类加载机制
    java面试问题分类
    ConcurrentHashMap总结
    ffmpeg对视频封装和分离
    SSM的整合
    单例模式的七种写法
    SecureCRT的快捷键
    linux下mysql常用命令
    maven操作
  • 原文地址:https://www.cnblogs.com/daocaorenblog/p/4894661.html
Copyright © 2011-2022 走看看