zoukankan      html  css  js  c++  java
  • Sort List

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

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *sortList(ListNode *head) {
            if(head==NULL||head->next==NULL){
                return head;
            }
           ListNode*r= mergeSort(head);
            return r;        
        }
       ListNode* mergeSort(ListNode *head){
           if(head==NULL||head->next==NULL){
               return head;
           }
            ListNode *p=head;
            ListNode *q=head;
            ListNode *pre=head;
            while(q!=NULL&&q->next!=NULL){//注意此处q的判断条件
                q=q->next->next;
                pre=p;
                p=p->next;
            }
            pre->next=NULL;//此处将分成两个子链表
            ListNode*s= mergeSort(head);
            ListNode*t=mergeSort(p);
           return merge(s,t);
            
        }
        ListNode * merge(ListNode*head,ListNode*p){
            ListNode* q=new ListNode(0);//申请一个节点,注意要释放
            ListNode* h1=q;
           
            while(head!=NULL&&p!=NULL){
                if(head->val<=p->val){
                    h1->next=head;
                    head=head->next;
                }else {
                    h1->next=p;
                    p=p->next;
                }
                h1=h1->next;            
            }
            if(p!=NULL){
                h1->next=p;           
            }
            if(head!=NULL){
                h1->next=head;
            }
            h1=q->next;
            q->next=NULL;
            delete(q);
            return h1;
            
        }
        
    };

     通过题意的nlogn可知,需要用归并或者快排思想,以上代码沿用了数组归并排序的实现思想,快排也可。

  • 相关阅读:
    BigDecimal的一些用法
    java文件读写实例
    2017java文本文件操作(读写操作)
    java一些必会算法
    代码规范、如何写出好代码
    File available()方法
    Java当中的JVM
    分布式锁机制
    异常处理---抛与踹
    while eles
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4394913.html
Copyright © 2011-2022 走看看