leetcode之Insertion Sort List
Sort a linked list using insertion sort.
这道题是用链表做插入排序。虽然之前数据结构中学习了链表的插入删除等,但那些都是最简单的基本操作,只是给出一个节点,直接给出插入位置。
首先,插入排序的思想是,每次将一个元素插入到前面已排序的有序的链表中,因此首先要找到需要插入的元素,如果链表的链接顺序是按照生序排列的话直接continue
当找到要插入的元素时,即第一个使得无序的元素。首先应该记录下当前元素的位置,以及该元素之前的位置。
其次开始从头遍历已排序的前面链表,直到找到要插入的位置
最后再用之前学习过的插入的基本操作。
整个题目思路相对来说比较清晰,只是一定要记住插入时几点next的顺序。
有一点不明白的地方是为什么要返回newHead.next?
下面附上源码
public ListNode insertionSortList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode cur = head;
ListNode post = head.next;
while(post!=null){
if(post.val>cur.val){
cur = cur.next;
post = post.next;
}
else{
ListNode insertCur = newHead;
ListNode insertPost = newHead.next;
while(insertPost.val<post.val){
insertCur = insertCur.next;
insertPost = insertPost.next;
}
cur.next = post.next;
post.next = insertPost;
insertCur.next = post;
post = cur.next;
}
}
return newHead.next;
}

浙公网安备 33010602011771号