[LeetCode OJ] Insertion Sort List 解题报告

地址:https://oj.leetcode.com/problems/insertion-sort-list/

题意:链表的插入排序

注意:所有和指针有关的代码都要非常注意边界处理。

要点:理解链表和数组的插入排序的不同,插入时链表不需要向后或向前移动,比数组的插入排序要快,但复杂度还是O(N2)。

#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
void insertNode(ListNode *head,ListNode *node){
    ListNode *ptr = head->next;
    ListNode *pre = head;
    bool flag = 0;
    while(ptr != NULL){
        if(ptr->val > node->val){
            pre->next = node;
            node->next = ptr;
            flag = 1;
            break;
        }
        pre = ptr;
        ptr = ptr->next;
    }
    if(flag == 0){
        pre->next = node;
        node->next = NULL;
    }
}

ListNode *insertionSortList(ListNode *head) {
    if(!head||!head->next) return head;
    ListNode L(0);
    ListNode *List = &L;
    ListNode *ptr = head;
    ListNode *node = NULL;
    while(ptr!=NULL){
        node = ptr;
        ptr = ptr->next;
        insertNode(List,node);
    }
    return List->next;
}
};
点赞