LeetCode | Insertion Sort List
2014-05-22 14:28
387 查看
原题描述:https://oj.leetcode.com/problems/insertion-sort-list/
Sort
a linked list using insertion sort.
解题思路:
通过插入法来实现单链表的排序:
外层循环体从链表第2个结点开始,依次扫描至尾结点,每一轮外层扫描结点记录为index。对于每一轮外层扫描,做如下操作:
1、确定插入点位置
从头结点开始扫描,依次比较所扫描结点的值与index结点的值,若index结点的值较大,则继续扫描,直到扫描到index结点为止。扫描结束以后,指针所在的位置即为要插入的点。
2、插入操作
最初我的想法是直接通过修改相关结点的next值来完成插入,后来发现这样操作会打破链表原有的秩序,很容易出错,所以最终选择了修改相关结点的val值来完成插入。首先,通过交换结点val值的方法,将插入位置到index结点之间的结点往后“移动”,以空出位置,然后将index结点的val值赋给插入点的val值即可。
代码实现:
Sort
a linked list using insertion sort.
解题思路:
通过插入法来实现单链表的排序:
外层循环体从链表第2个结点开始,依次扫描至尾结点,每一轮外层扫描结点记录为index。对于每一轮外层扫描,做如下操作:
1、确定插入点位置
从头结点开始扫描,依次比较所扫描结点的值与index结点的值,若index结点的值较大,则继续扫描,直到扫描到index结点为止。扫描结束以后,指针所在的位置即为要插入的点。
2、插入操作
最初我的想法是直接通过修改相关结点的next值来完成插入,后来发现这样操作会打破链表原有的秩序,很容易出错,所以最终选择了修改相关结点的val值来完成插入。首先,通过交换结点val值的方法,将插入位置到index结点之间的结点往后“移动”,以空出位置,然后将index结点的val值赋给插入点的val值即可。
代码实现:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode insertionSortList(ListNode head) { if (head == null || head.next == null) return head; ListNode index = head.next; while (index != null) { ListNode temp = head; //定位到要插入的位置 while (temp.val < index.val && temp != index) temp = temp.next; //“移动”插入点后面的元素 if (temp != index) { while (temp != index) { //交换两个结点的值,而不是修改next值 int t = temp.val; temp.val = index.val; index.val = t; temp = temp.next; } } index = index.next; } return head; } }
相关文章推荐
- LeetCode147: Insertion Sort List
- [LeetCode] Insertion Sort List
- leetCode(4):Insertion Sort List 分类: leetCode 2015-06-17 09:42 205人阅读 评论(0) 收藏
- [LeetCode]Insertion Sort List
- [LeetCode]Insertion Sort List
- leetcode_147 Insertion Sort List
- LeetCode-Insertion Sort List
- [LeetCode 题解]: Insertion Sort List
- LeetCode: Insertion Sort List
- LeetCode Insertion Sort List 链表的插入排序
- Leetcode Insertion Sort List
- Insertion Sort List —— Leetcode
- [LeetCode]题解(python):147-Insertion Sort List
- [leetcode] Insertion Sort List
- leetcode InsertionSort list
- [C++]LeetCode: 126 Insertion Sort List (插入排序链表)
- leetcode 147: Insertion Sort List
- LeetCode 之 Insertion Sort List — C++ 实现
- leetcode - Insertion Sort List
- LeetCode----Insertion Sort List