147.Insertion Sort List---链表排序(直接插入)

题目连接ide

题目大意:对链表进行插入排序。post

解法:直接插入排序。代码以下(耗时40ms):spa

 1     public ListNode insertionSortList(ListNode head) {
 2         ListNode first = new ListNode(0);
 3         ListNode pre = first, cur = head, post = null;
 4         while(cur != null) {
 5             //保存cur.next,由于要遍历当前结点,下一次就要遍历当前结点的下一个结点,因此在此次遍历完以后须要从新赋值cur=post
 6             post = cur.next;
 7             //寻找能够插入的结点位置
 8             while(pre.next != null && pre.next.val < cur.val) {
 9                 pre = pre.next;
10             }
11             //找到以后,将cur结点插入在pre和pre.next之间
12             cur.next = pre.next;
13             pre.next = cur;
14             //下一次pre再从头开始找可插入的结点位置,因此要置为开始头节点
15             pre = first;
16             //下一次对cur.next结点进行排序,因此要将cur置回
17             cur = post;
18         }
19         return first.next;
20     }
View Code
相关文章
相关标签/搜索