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
- LeetCode之147_Insertion Sort List
- leetcode第一刷_Insertion Sort List
- leetcode之Sort List
- leetcode之Sort List
- leetcode之Sort List
- LeetCode之Sort List
- leetcode之Sort List
- Leetcode之Sort List
- leetcode之sort-list
- leetcode之Insertion Sort List
- leetcode之Insertion Sort List
- leetcode之Insertion Sort List
- leetcode之Insertion Sort List
- LeetCode之Insertion Sort List
- leetcode之insertion Sort list
- leetcode之insertion-sort-list
- leetcode之insertion-sort-list
- LeetCode(147) Insertion Sort List
- Android Volley完全解析(三),定制自己的Request
- HDU—— 4932 Miaomiao's Geometry
- Openvswitch手册(4): Mirror
- Spring MVC 中 HandlerInterceptorAdapter的使用
- dedecms增加php函数功能及在列表页获取当前栏目的文章数
- LeetCode之147_Insertion Sort List
- SharedSDK微信分享不成功,分享之后没有反应
- C++ 类的聚集和浅拷贝与深拷贝
- dwqfqw
- AD属性对照表
- 第10周项目6贪财的富翁
- PostgreSQL的行转列函数使用一例
- feqfgqef
- How to add the CAPTCHA functionality in salesforce