LeetCode 147 Insertion Sort List(链表)

来源:互联网 发布:2200万淘宝买家资料 编辑:程序博客网 时间:2024/06/04 00:46

Sort a linked list using insertion sort.

代码如下:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */ void swap(int* a, int* b) {     int tmp = *a;     *a = *b;     *b = tmp; }struct ListNode* insertionSortList(struct ListNode* head) {    struct ListNode* ptr;    if(!head) return NULL;    for(ptr = head->next;ptr;ptr = ptr->next){        for(struct ListNode* tmp = head;tmp != ptr;tmp = tmp->next){            if(tmp->val > ptr->val) swap(&ptr->val, &tmp->val);        }    }    return head;}

0 0
原创粉丝点击