Insertion Sort List

本文介绍了一种使用插入排序算法对链表进行排序的方法,通过创建一个新的链表来实现排序过程,便于操作。详细解释了算法步骤,并提供了代码实现。

Insertion Sort List

Sort a linked list using insertion sort.

这道题用两个链表做的,这样方便一点。还有新链表头结点我没有存放内容,这样也比较方便,后面返回head1.next就好了

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode insertionSortList(ListNode head) {
14         ListNode head1 = new ListNode(0);
15         if(null == head || null == head.next)
16             return head;
17         
18         else{            
19             ListNode temp = new ListNode(0);
20             temp.val = head.val;
21             temp.next = null;
22             head1.next = temp;//用一个新链表
23             
24             ListNode ptr = head.next;
25             while(ptr != null){        //遍历原来的链表,插入到新链表中
26                 temp = head1.next;
27                 ListNode tempPre = head1;            //temp前面的节点
28                 while(temp != null){
29                     if(temp.val > ptr.val){            //在temp前面插入结点
30                         ListNode nodeAdd = new ListNode(0);
31                         nodeAdd.val = ptr.val;
32                         nodeAdd.next = temp;
33                         tempPre.next = nodeAdd;
34                         break;                        //插入完成,跳出循环
35                     }
36                     temp = temp.next;
37                     tempPre = tempPre.next;
38                 }
39                 if(null == temp){                    //在新链表添加节点
40                     ListNode nodeAdd = new ListNode(0);
41                     nodeAdd.val = ptr.val;
42                     nodeAdd.next = null;
43                     tempPre.next = nodeAdd;
44                 }
45                 ptr = ptr.next;
46             }
47         }
48         
49         return head1.next;
50     }
51 }

 

转载于:https://www.cnblogs.com/luckygxf/p/4119865.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值