链表插入排序-LintCode

来源:互联网 发布:电信4g网络信号不好 编辑:程序博客网 时间:2024/05/21 10:17

用插入排序对链表排序
样例
Given 1->3->2->0->null, return 0->1->2->3->null

#ifndef C173_H#define C173_H#include<iostream>using namespace std;class ListNode{public:    int val;    ListNode *next;    ListNode(int val)    {        this->val = val;        this->next = NULL;    }};class Solution {public:    /**    * @param head: The first node of linked list.    * @return: The head of linked list.    */    ListNode *insertionSortList(ListNode *head) {        // write your code here        if (head == NULL)            return NULL;        ListNode *p = head;        ListNode *node =new ListNode(-1);        while (p != NULL)        {            ListNode *q = node;            if (p == head)            {                node->next = new ListNode(p->val);            }            else            {                ListNode *p1 = node->next;                while (p1!=NULL)                {                    if (p->val >= p1->val)                    {                        if (p1->next == NULL)                        {                            p1->next = new ListNode(p->val);                            break;                        }                        else                        {                            p1 = p1->next;                            q = q->next;                        }                    }                    else                    {                        ListNode *l = new ListNode(p->val);                        l->next = q->next;                        q->next = l;                        break;                    }                }            }            p = p->next;        }        return node->next;    }};#endif
原创粉丝点击