LeetCode之147_Insertion Sort List

来源:互联网 发布:linux mysql安装详解 编辑:程序博客网 时间:2024/06/06 07:11

题目:

Sort a linked list using insertion sort.

分析:

单链表的剪切和插入操作,唯一需要注意的是边界的处理和插入新节点到链表头的情况

代码:

#include<iostream>using namespace std;//Sort a linked list in O(n log n) time using constant space complexity.//尝试使用归并排序,待排序元素为单链表struct ListNode {int val;ListNode *next;};class Solution {public:ListNode *insertionSortList(ListNode *head) {if (head == NULL){return NULL;}ListNode *retHead = head;ListNode *sortedNode = head;ListNode *preNode = head;int value = 0;while( sortedNode != NULL && sortedNode->next != NULL){head = retHead;preNode = retHead;value = sortedNode->next->val;while (head != sortedNode->next ){if (head->val < value){preNode = head;head = head->next;}else{ListNode *tempNode = CutNode(sortedNode);    //把要插入的节点从链表中剪切下来,即sortedNode的下一个节点if (head == retHead){retHead = InsertNode(NULL,tempNode,&retHead);   //要插入到链表头部,需要更改返回的头指针}elseInsertNode(preNode,tempNode,&retHead);  //正常插入break;}}if (head == sortedNode->next){sortedNode = sortedNode->next;}}return retHead;}ListNode *CutNode(ListNode* nodeLoction){ListNode *nodeRet = nodeLoction->next;nodeLoction->next = nodeRet->next;return nodeRet;}ListNode* InsertNode(ListNode* sortNode,ListNode* nodeInsert, ListNode** head){if (sortNode == NULL)   //插入到头结点{nodeInsert->next = *head;*head = nodeInsert;}else               //正常插入到链表中{nodeInsert->next = sortNode->next;sortNode->next = nodeInsert;}return *head;}};void printList(ListNode* head){cout<<endl;while (head != NULL){cout<<head->val<<" ";head=head->next;}cout<<endl;}int main(){ListNode *head = new ListNode;ListNode *tail = head;head->val = 45;head->next = NULL;for (int i = 0; i< 19; i++){ListNode* temp = new ListNode;temp->val = rand()%90;temp->next = NULL;tail->next = temp;tail = tail->next;}printList(head);Solution a;head = a.insertionSortList(head);printList(head);system("pause");return 0;}
提交到LeetCode时只需提交类内的几个函数即可



0 0
原创粉丝点击