算法:链表的插入排序

来源:互联网 发布:好听的淘宝会员名 编辑:程序博客网 时间:2024/06/05 16:10

LeetCode OJ 编程题: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) {        if((head == NULL) || (head->next == NULL))            return head;        ListNode *p, *pre_q, *q, *temp;        p = head->next;        head->next = NULL;        while(p != NULL)        {            pre_q = q = head;            //q = head->next;            while((q != NULL) && (q->val <= p->val))            {                pre_q = q;                q = q->next;            }                        //当头结点的值大于要比较的结点时            if((q == head) && (q->val > p->val))            {                temp =p;                p = p->next;                temp->next = head;                head = temp;            }            else            {                temp = p;                p = p->next;                pre_q->next = temp;                temp->next = q;            }                    }        return head;            }};


0 0