题目描述
Sort a linked list using insertion sort.
一般思路(直接在原链表上进行插排)
很好理解,就是遍历每个结点cur,同时记录其前一个结点pre。
如果碰到某个cur的值小于pre,从头结点开始遍历,直到找到应该插入的位置。
不使用哑结点的问题就是多判断了一个cur要替换头结点,头结点往后移的状况,这时不能用遍历的代码
需要额外写一种情况
if(head.val > cur.val){
cur.next = head;
head = cur;
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public static ListNode insertionSortList(ListNode head) {
if(head == null || head.next == null)return head;
for(ListNode pre = head; pre.next != null; ){

本文探讨了在链表排序中哑结点的作用,通过插入排序算法进行说明。通常做法是在原链表上直接进行排序,但会遇到判断和处理头结点的特殊情况。引入哑结点后,创建一个虚拟的新链表,避免了替换头结点的问题,简化了代码逻辑。使用哑结点使得查找插入位置更加直观,提高了效率。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



