C实现 LeetCode->Merge Two Sorted Lists (双指针大法)


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

 *   将单链表 排序   O(n lg n)

  

C实现 LeetCode->Merge Two Sorted Lists (双指针大法)_第1张图片


//
//  SortList.c
//  Algorithms
//
//  Created by TTc on 15/6/18.
//  Copyright (c) 2015年 TTc. All rights reserved.
//

/**
 *  Sort a linked list in O(n log n) time using constant space complexity.
 *   将单链表 排序
*/
#include "SortList.h"


struct ListNode {
    int val;
    struct ListNode *next;
};

/**
 *   双指针大法,创建两个 指针(首尾指针 向中间扫描)
 */
struct ListNode*
sortList(struct ListNode* head) {
    if(!head)  return NULL;
    
    struct ListNode *start = head;
    struct ListNode *end = head;
    
    
    int length = 0;
    while(start)  {
        length++;
        start = start->next;
    }
    
    if(length == 1)   return head;
    
    int mid = length/2;    //计算结点个数,将链表分开。
    
    //将链表分开
    struct ListNode *tmpNode = NULL;
    
    for(int i = 0; i < mid && end != NULL; i++)  {
        if(i == mid - 1) tmpNode = end;
        end = end->next;
    }
    
    if(tmpNode != NULL) tmpNode->next = NULL;
    
    //分别对两段排序
    start = head;
    start = sortList(start);
    end   = sortList(end);
    
    struct ListNode *newhead = NULL;//新创建的list头节点
    struct ListNode *newtemp = NULL;//中间遍历接收变量
    
    while(start && end) {  //合并
        if(start->val <= end->val)  {
            if(!newhead)  newtemp = newhead = start;
            else{
                newtemp->next = start;
                newtemp = start;
            }
            start = start->next;
        }else{
            if(!newhead) newhead = newtemp = end;
            else{
                newtemp->next = end;
                newtemp = end;
            }
            end = end->next;
        }
    }
    if(start) newtemp->next = start;
    if(end) newtemp->next = end;
    return newhead;
}



你可能感兴趣的:(C实现 LeetCode->Merge Two Sorted Lists (双指针大法))