zoukankan      html  css  js  c++  java
  • 143. Reorder List

    Given a singly linked list LL0→L1→…→Ln-1→Ln,
    reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

    You may not modify the values in the list's nodes, only nodes itself may be changed.

    Example 1:

    Given 1->2->3->4, reorder it to 1->4->2->3.

    Example 2:

    Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

    重新排列链表
    1->2->3->4->5 to 1->5->2->4->3.

    C++:

     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)
    13             return ;
    14         ListNode* p1 = head ;
    15         ListNode* p2 = head ;
    16         while(p2->next != NULL && p2->next->next != NULL){
    17             p1 = p1->next ;
    18             p2 = p2->next->next ;
    19         }
    20         
    21         //1->2->3->4->5->6 to 1->2->3->6->5->4
    22         ListNode* head2 = p1->next ;
    23         p1->next = NULL ;
    24         
    25         p2 = head2->next ;
    26         head2->next = NULL;
    27         while(p2 != NULL){
    28             p1 = p2->next ;
    29             p2->next = head2 ;
    30             head2 = p2 ;
    31             p2 = p1 ;
    32         }
    33 
    34         // 1->2->3->6->5->4 to 1->6->2->5->3->4
    35         p1 = head ;
    36         p2 = head2 ;
    37         while(p1 != NULL){
    38             ListNode* t = p1->next ;
    39             p1->next = p2 ;
    40             p1 = p2 ;
    41             p2 = t ;
    42         }
    43     }
    44 };
  • 相关阅读:
    JS —— 数组与字符串方法
    CSS —— 选择器
    HTML —— 小记
    Javascript学习记录——数组去重
    尝鲜 vue3.x 新特性
    Weex项目快速打包
    揭秘C# SQLite的从安装到使用
    Javascript中Promise的简单使用
    网页背景图片的淡入淡出效果
    部分标点符号和数学符号的英文名字
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/10606261.html
Copyright © 2011-2022 走看看