Insertion Sort List
Sort a linked list using insertion sort.
- 思想: 保持四个指针,循环last和p,以及从前向后插入的两个指针pre和q。
- 注意:几个指针之间的关系
- public ListNode insertionSortList(ListNode head) {
- if(head == null || head.next == null) return head;
- ListNode p = head.next;
- ListNode last = head;
- while(p!=null) {
- ListNode q = head;
- ListNode pre = head;
- while(p.val > q.val) {
- pre = q;
- q=q.next;
- }
- if(q==head) {
- last.next = p.next;
- p.next = head;
- head = p;
- } else if(q==p) {
- last = p;
- } else {
- last.next = p.next;
- pre.next = p;
- p.next = q;
- }
- p = last.next;
- }
- return head;
- }

浙公网安备 33010602011771号