力扣147-链表的插入排序

在这里插入图片描述

思路:

1.创建一个新的链表

2.对原链表进行头删

3.在新链表找插入的合适位置(保证插入后链表有序)

4.将头删的结点插入到新链表的合适位置处(头插操作和中间插尾插不相同)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

typedef struct ListNode Node;
struct ListNode* insertionSortList(struct ListNode* head){
    
    
    if(head == NULL || head->next == NULL)
    {
    
    
        return head;
    }//没有节点和只有一个结点不需要插入排序
    Node *nhead = head;
    head = head->next;
    nhead->next = NULL;//新建一个链表,该链表有序,并且将原链表的第一个结点直接插入
    while(head)
    {
    
    
        Node *cur = head;
        head = head->next;//头删,取下原链表的第一个结点
        Node *insert = nhead,*pre = NULL;
        while( insert && cur->val > insert->val)
        {
    
    
            pre = insert;
            insert = insert->next;
        }//找到插入的合适位置,保证新的链表有序
       if(insert == nhead)
        {
    
    
            cur->next = insert;
            nhead = cur;
        }//头插
        else//cur->val <= insert->val
        {
    
    
            cur->next = insert;
            pre->next = cur;
        }//中间插和尾插操作相同
    }
    return nhead;
}

猜你喜欢

转载自blog.csdn.net/weixin_50168448/article/details/112017519