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


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

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

  



//
//  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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值