Leetcode | Insertion Sort List | 初出茅庐

来源:互联网 发布:unity3d 材质球shader 编辑:程序博客网 时间:2024/06/07 03:26

Insertion Sort List

 Total Accepted: 11143 Total Submissions: 45047My Submissions

Sort a linked list using insertion sort.


这题目比较简单,基本代码一看就明白,试试便知。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *insertionSortList(ListNode *head) {    ListNode *search, *last, *next;        if(head == NULL)    return head;        last = head;    while(last->next != NULL)    {    next = last->next;    if(next->val >= last->val)    last = last->next;    else    {    if(next->val <= head->val)    {    last->next = next->next;    next->next = head;    head = next;    }    else    {    search = head;    while(next->val > search->next->val)    search = search->next;    last->next = next->next;    next->next = search->next;    search->next = next;    }        }    }        return head;            }};

0 0