您的位置:首页 > 编程语言 > Java开发

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值即可。

代码实现:

/**
* 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息