题目描述:
Sort a linked list using insertion sort.
Algorithm of Insertion Sort:
- Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
- At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
- It repeats until no input elements remain.
单链表的定义:
1 | public class ListNode { |
想法:
使用两条链表,一条是已经有序的链表 A,一条是待排序的链表 B。将节点从待排序的链表 B 依次插入已经有序的链表 A。
关键点在于想到使用两条链表。
代码:
1 | class Solution { |