leetcode No147. Insertion Sort List

来源:互联网 发布:linux运行中结束进程 编辑:程序博客网 时间:2024/06/01 07:59

Question:

Sort a linked list using insertion sort.

Algorithm:

新建一个链表,模仿插入排序的过程

Accepted Code:

/** * 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* curHead=new ListNode(INT_MIN);   //避免对头结点操作        if(head==NULL || head->next==NULL)            return head;        ListNode* pNode=head;      //遍历head的结点        while(pNode){            ListNode* tmp=pNode->next;  //pNode是要插入的结点,tmp要保存pNode->next;            ListNode* pPre=curHead;     //插入点前结点            ListNode* pNext=curHead->next;  //插入点后结点            while(pNext && (pNext->val<pNode->val)){                pPre=pPre->next;                pNext=pNext->next;            }            pPre->next=pNode;            pNode->next=pNext;            pNode=tmp;        }        return curHead->next;    }};



0 0
原创粉丝点击