您的位置:首页 > 其它

leetcode-147 Insertion Sort List

2015-03-14 12:06 387 查看
题目要求使用插入排序

因为是链表,所以加上一个辅助头节点(这个思想在链表的操作中经常用到)

这题本来是没有什么难度的

<span style="font-family:Microsoft YaHei;font-size:14px;">/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *insertionSortList(struct ListNode *head) {
    if(head == NULL)
        return NULL;
    struct ListNode helper;
    struct ListNode *cur;
    struct ListNode *next;
    struct ListNode *pre;
    
    helper.next = NULL;
    cur = head;
    pre = &helper;
    next = NULL;
    
    while(cur != NULL){
        next = cur->next;
        while( (pre->next != NULL) && (pre->next->val < cur->val) ){
            pre = pre->next;
        }
        
        cur->next = pre->next;
        pre->next = cur;
        pre = &helper;
        cur = next;
    }
    return helper.next;
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: