147. Insertion Sort List
来源:互联网 发布:netbeans python插件 编辑:程序博客网 时间:2024/04/19 07:46
Sort a linked list using insertion sort.
解法:
Well, life gets difficult pretty soon whenever the same operation on array is transferred to linked list.
First, a quick recap of insertion sort:
Start from the second element (simply a[1] in array and the annoying head -> next -> val in linked list), each time when we see a node with val smaller than its previous node, we scan from the head and find the position that the current node should be inserted. Since a node may be inserted before head, we create a new_head that points to head. The insertion operation, however, is a little easier for linked list.
Now comes the 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) { if(!head||!head->next) return head; ListNode* new_head ; new_head->next = head; ListNode* pre = new_head; ListNode* cur = head; while(cur) { if(cur->next && cur->next->val < cur->val) { while(pre->next && pre->next->val < cur->next->val) pre = pre->next; ListNode* temp = pre->next; pre->next = cur->next; cur->next = cur->next->next; pre->next->next = temp; pre = new_head; } else cur = cur->next; } return new_head->next; }};
方法二:
class Solution {public: /** * @param head: The first node of linked list. * @return: The head of linked list. */ ListNode *insertionSortList(ListNode *head) { ListNode *dummy = new ListNode(0); // 这个dummy的作用是,把head开头的链表一个个的插入到dummy开头的链表里 // 所以这里不需要dummy->next = head; while (head != NULL) { ListNode *temp = dummy; ListNode *next = head->next; while (temp->next != NULL && temp->next->val < head->val) { temp = temp->next; } head->next = temp->next; temp->next = head; head = next; } return dummy->next; }};
0 0
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 我的开心的事情
- Hibernate三种状态的区分,以及save,update,saveOrUpdate,merge等的使用
- WebSocket聊天客户端
- 广告图片滚动播放ViewPage
- 一个简单的开始加载界面
- 147. Insertion Sort List
- HTML特殊符号显示技巧
- POJ 1054 Java: The Troublesome Frog
- 使用opencv作物件识别(一) —— 积分直方图加速HOG特征计算
- objdump命令的使用
- Chapter 4 使用Nova搭建云平台控制器
- 数据泵expdp/impdp工具的使用:
- 车型识别“Hyper-class Augmented and Regularized Deep Learning for Fine-grained Image Classification”
- 《VR入门系列教程》之17---发布第一个应用