首页 > 代码库 > Leetcode - Insertion Sort List
Leetcode - Insertion Sort List
It is quite a basic problem. However I spent half an hour solving it and made two mistakes. Guess it‘s because I haven‘t written some fundamental data structures like linked list for a while and kind of get lost. I should practice these questions more.
public class Solution { public ListNode insertionSortList(ListNode head) { if (head == null || head.next == null) return head; ListNode cNode = head.next; ListNode prevcNode = head; while (cNode != null) { if (cNode.val <= head.val) { prevcNode.next = cNode.next; cNode.next = head; head = cNode; cNode = prevcNode.next; } else { ListNode tNode = head; while( tNode.next != cNode &&tNode.next.val < cNode.val) { tNode = tNode.next; } if(tNode.next == cNode) { prevcNode = cNode; cNode = cNode.next; } else { prevcNode.next = cNode.next; cNode.next = tNode.next; tNode.next = cNode; cNode = prevcNode.next; } } } return head; } }
Leetcode - Insertion Sort List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。