標籤:leetcode algorithm java 插入排序 鏈表
Sort a linked list using insertion sort.
【題意】
用插入排序對一個鏈表進行排序。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
【思路】
基礎題。痛點在於理解鏈表結,因為 next 既是當前 node 的屬性,又表示下一個 node。
在 head 之前添加一個新的頭 newhead,因為插入排序時可能有 node 要插在 head 之前,這時就需要這個 newhead 的協助。
【Java代碼】
public class Solution { public ListNode insertionSortList(ListNode head) { if (head == null || head.next == null) return head;//新手很容易忽略這一行 ListNode newhead = new ListNode(0); newhead.next = head;//在head前添加一個新頭newhead ListNode p = head.next;//遍曆從第二個node開始 head.next = null;//目前已排序的鏈表只有newhead和head兩個結點,這樣做的好處是如果後面插入的結點都在head之前,那麼可以保證排完序的鏈表結尾指向null while (p != null) {//用p遍曆還未排序的鏈表 ListNode cur = p; p = p.next; cur.next = null;//如果這個結點需要查到鏈表的最後,這樣做可以保證鏈表結尾指向null ListNode node = newhead.next; ListNode pre = newhead; while (node != null) {//用node遍曆已排好序的鏈表,pre表示遍曆時當前項的前一項 if (cur.val < node.val) {//在該插入的位置插入cur pre.next = cur; cur.next = node; break; } else {//還未到插入的位置,繼續向後,同時更新pre pre = node; node = node.next; } if (node == null) {//如果插入的位置在鏈表末尾 pre.next = cur; } } } return newhead.next; }}
不多說了,捋清思路,分清楚哪個是變數,哪個是鏈表中的項。混亂時不妨從頭再來。
【LeetCode】Insertion Sort List