[leetcode] Insertion Sort List

来源:互联网 发布:淘宝 摄魂猎手vn 编辑:程序博客网 时间:2024/05/02 01:49

Insertion Sort List

#include "iostream"using namespace std;/**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=head->next;//待排序        ListNode *res =new ListNode(0);//已排序        res->next=head;        head->next=NULL;                ListNode *preq=res;        ListNode *q=preq->next;                while (p!=NULL) {                        while (q!=NULL&&p->val>q->val) {                preq=q;                q=q->next;            }                        preq->next=p;            p=p->next;            preq=preq->next;            preq->next=q;                        preq=res;            q=preq->next;        }                res->next=NULL;        delete res;        return q;    }};int main() {    ListNode *t=new ListNode(3);    t->next=new ListNode(2);    t->next->next=new ListNode(1);    cout<<t->val<<endl;    Solution so;    ListNode *res= so.insertionSortList(t);    cout<<res->val<<res->next->val<<endl;    return 0;}


0 0
原创粉丝点击