博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Insertion Sort List
阅读量:6927 次
发布时间:2019-06-27

本文共 1530 字,大约阅读时间需要 5 分钟。

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:

1 class Solution {  2 public: 3     ListNode* insertionSortList(ListNode* head) { 4         ListNode* new_head = new ListNode(0); 5         new_head -> next = head; 6         ListNode* pre = new_head; 7         ListNode* cur = head; 8         while (cur) { 9             if (cur -> next && cur -> next -> val < cur -> val) {10                 while (pre -> next && pre -> next -> val < cur -> next -> val)11                     pre = pre -> next;12                 /* Insert cur -> next after pre.*/13                 ListNode* temp = pre -> next;14                 pre -> next = cur -> next;15                 cur -> next = cur -> next -> next;16                 pre -> next -> next = temp;17                 /* Move pre back to new_head. */18                 pre = new_head;19             }20             else cur = cur -> next;21         }22         ListNode* res = new_head -> next;23         delete new_head;24         return res;25     }26 };

 

转载地址:http://fmujl.baihongyu.com/

你可能感兴趣的文章
SharePoint 2013 实现多级审批工作流
查看>>
Java泛型详解
查看>>
原创Java版的Shell
查看>>
windows phone (18) Border元素
查看>>
后端安全验证过程
查看>>
基于linux2.6.38.8内核启动过程完全解析[一]
查看>>
如何设置路由器实现静态IP配置
查看>>
4.3 spring-嵌入式beans标签的解析
查看>>
C#可以获取Excel文件中Sheet的名字
查看>>
Windows XP系统服役13年今正式退休
查看>>
HDUOJ---3743Frosh Week(BIT+离散化)
查看>>
Codeforces Round #238 (Div. 2) D. Toy Sum
查看>>
python zookeeper 学习笔记
查看>>
yii 获取当前ip
查看>>
iOS开发UI篇—使用xib自定义UItableviewcell实现一个简单的团购应用界面布局
查看>>
linux和windows文件名称长度限制
查看>>
从零开始学摄影
查看>>
Junit单元测试笔记
查看>>
php 分页类
查看>>
Android中pm命令用法(转)
查看>>