zoukankan      html  css  js  c++  java
  • [Leetcode] Reorder List

    Given a singly linked list LL0L1→…→Ln-1Ln,
    reorder it to: L0LnL1Ln-1L2Ln-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}.

    OH! MY GOD! I HATE LINKED 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 class Solution {
    10 public:
    11     void reverseList(ListNode *&head) {
    12         ListNode *h = new ListNode(0);
    13         ListNode *tmp;
    14         while (head != NULL) {
    15             tmp = head->next;
    16             head->next = h->next;
    17             h->next = head;
    18             head = tmp;
    19         }
    20         head = h->next;
    21     }
    22 
    23     void twistList(ListNode *&l1, ListNode *&l2) {
    24         ListNode *p1, *p2, *tmp;
    25         p1 = l1; p2 = l2;
    26         while (p1 != NULL && p2 != NULL) {
    27             tmp = p2->next;
    28             p2->next = p1->next;
    29             p1->next = p2;
    30             p1 = p1->next->next;
    31             p2 = tmp;
    32         }
    33     }   
    34 
    35     void reorderList(ListNode *head) {
    36         if (head == NULL || head->next == NULL || head->next->next == NULL) {
    37             return;
    38         }
    39         ListNode *slow, *fast;
    40         slow = head; fast = head;
    41         while (fast != NULL && fast->next != NULL) {
    42             slow = slow->next;
    43             if (fast->next->next == NULL) {
    44                 break;
    45             }
    46             fast = fast->next->next;
    47         }
    48         ListNode *l2 = slow->next;
    49         slow->next = NULL;
    50         reverseList(l2);
    51         twistList(head, l2);
    52     }
    53 };
  • 相关阅读:
    Improve Your Study Habits
    js中的cookie的读写操作
    js中数组/字符串常用属性方法归纳
    前端的一些常用DOM和事件归纳
    关于scroll无法绑定的问题
    页面内锚点定位及跳转方法总结
    js共享onload事件
    JS获取终端屏幕、浏览窗口的相关信息
    jsonp跨域问题记录
    关于if/else if
  • 原文地址:https://www.cnblogs.com/easonliu/p/3642822.html
Copyright © 2011-2022 走看看