Leetcode刷题记——147. Insertion Sort List(插入排序链表)

一、题目叙述:

Sort a linked list using insertion sort.

二、解题思路:

Medium题,啊。。。我今天头晕脑胀,写的不太顺利。代码之混乱,我现在提交成功了都还很迷。

使用插入排序的方法对链表进行排序,即每次和前面的结点比找到合适的位置插入,链表不同于数组的地方在于,只能从前往后比,找到第一个比目前结点值大的结点,插入到这个结点前面即可。

思路:

(1)先注意链表为空及链表只是单结点的情况,直接返回头指针即可。

(2)从链表第二个结点开始往后循环, 每个结点i都与从头结点开始的各个结点j比较(此处为之后操作记录下i和j之前的结点remi,remj),碰到第一个值比其大的结点:创建与i值相同的新结点,把新节点放在j结点前,删掉i结点,重新定义i的位置,跳出循环,i指针后移。以此类推直至i为null。

三、源码:

public class Solution  
{  
	
	public ListNode insertionSortList(ListNode head)
	{
	       if (head == null || head.next == null) return head;
	       ListNode remi, remj;
	       ListNode i = head.next;
	       remi = head;
	       while (i != null)
	       {
	    	   remj = head;
	    	   ListNode j = head;
	    	   while (j != i) 
	    	   {
	    		   if (j.val > i.val)
	    		   {
	    			   if (j == head)
	    			   {
	    			   ListNode frs = new ListNode(i.val);
	    			   frs.next = head;
	    			   remi.next = i.next;
	    			   head = frs;
	    			   i = remi;
	    			   }
	    			   else
	    			   {
	    				ListNode frs = new ListNode(i.val);
	    				remj.next = frs;
	    				frs.next = j;
	    				remi.next = i.next;
	    				i = remi;
	    			   }
	    			   break;
	    		   }
	    		   remj = j;
	    		   j = j.next;
	    	   }
	    	   remi = i;
	    	   i = remi.next;
	       }
	       return head;
	}
    public static void main(String args[])      
    {      
             
    	ListNode a = new ListNode(3);
    	ListNode first = a;
    	a.next = new ListNode(2);
    	a = a.next;
    	a.next = new ListNode(1);
    	//String a = "";
    	//String b = "";
      //  int[] digits = {0};      
        Solution solution = new Solution();      
     //   int[][] abc = {{2}};  
      //  int[] b = {2,3,4};  
       // for(int i = 0; i < abc.length; i ++)      
      ListNode res = solution.insertionSortList(first);
      while (res != null)
      {
    	  System.out.print(res.val); 
    	  res = res.next;
      }
    }      
}  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值