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

    Sort a linked list in O(n log n) time using constant space complexity.

    归并排序!用慢指针、快指针来寻找二分位置,这里很容易出现错,要特别注意。

     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     ListNode *mergeSort(ListNode *l1, ListNode *l2) {
    12         ListNode *head = new ListNode(-1);
    13         ListNode *pos = head;
    14         while (l1 != NULL && l2 != NULL) {
    15             if (l1->val < l2->val) {
    16                 pos->next = l1;
    17                 l1 = l1->next;
    18             } else {
    19                 pos->next = l2;
    20                 l2 = l2->next;
    21             }
    22             pos = pos->next;
    23         }
    24         if (l1 == NULL) pos->next = l2;
    25         if (l2 == NULL) pos->next = l1;
    26         return head->next;
    27     }
    28     
    29     ListNode *sortList(ListNode *head) {
    30         if (head == NULL || head->next == NULL) return head;
    31         ListNode *slow = head, *fast = head;
    32         while (fast != NULL && fast->next != NULL) {
    33             if (fast->next) fast = fast->next;
    34             else break;
    35             if (fast->next) fast = fast->next;
    36             else break;
    37             if (slow) slow = slow->next;
    38         }
    39         ListNode *head2 = slow->next;
    40         slow->next = NULL;
    41         head = sortList(head);
    42         head2 = sortList(head2);
    43         return mergeSort(head, head2);
    44     }
    45 };
  • 相关阅读:
    Linux系统命令与权限
    有关Linux目录相关内容
    Linux的命令以及基本使用
    操作系统的基本知识与Linux系统简介
    IT知识架构与操作系统简介
    windows下nginx支持php的配置
    提权操作函数
    c++内存中字节对齐问题详解 [ 转载 ]
    STL 容器效率的对比
    C++ 四种类型转换的介绍
  • 原文地址:https://www.cnblogs.com/easonliu/p/3651861.html
Copyright © 2011-2022 走看看