描述:
Sort a linked list using insertion sort.
思路:
实现对链表的插入排序,显然,只能从头开始对链表进行插入排序了,时间复杂度O(n*n)
代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode insertionSortList(ListNode head) { if(head==null||head.next==null) return head; ListNode newHead=new ListNode(0); newHead.next=head; ListNode temp=null,p=head,q=null; while(p.next!=null) { if(p.val<=p.next.val) { p=p.next; }else { temp=p.next; p.next=p.next.next; q=newHead; while(q!=p) { if(temp.val<q.next.val) { temp.next=q.next; q.next=temp; break; } q=q.next; } } } return newHead.next; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-09 12:00:27