本文主要是介绍leetcode No147. Insertion Sort List,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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;}
};
这篇关于leetcode No147. Insertion Sort List的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!