LeetCode-Insertion Sort List[AC源碼]

來源:互聯網
上載者:User

標籤:des   style   blog   color   os   io   for   ar   

 1 package com.lw.leet5; 2  3 /** 4  * @ClassName:Solution 5  * @Description: 6  *         Insertion Sort List  7  *         Sort a linked list using insertion sort. 8  * @Author LiuWei 9  * @Date 2014年8月20日下午7:50:0710  * @Mail [email protected] 11  */12 public class Solution {13 14     public ListNode insertionSortList(ListNode head) {15         // if only one or two elements ,return head16         if(head == null || head.next == null){17             return head;18         }19         ListNode cur = head.next;20         ListNode tmp = null;21         while(cur != null){22             tmp = head;23             //get the insertion position24             while(tmp != cur && tmp.val < cur.val){25                 tmp = tmp.next;26             }27             //if need insert, switch the value28             if(tmp != cur){29                 int num1 = cur.val;30                 int num2 ;31                 while(tmp != cur){32                     //store the tmp value33                     num2 = tmp.val;34                     tmp.val = num1;35                     num1 = num2;36                     tmp = tmp.next;37                 }38                 //init cur39                 tmp.val = num1;40             }41             cur = cur.next;42         }43         return head;44     }45 46     public static void main(String args[]) {47         int[] arr = {10,3,2,4,0,0,-1,2,-2};48          ListNode head = new ListNode(arr[0]);49          ListNode curr = head;50          for(int i=1; i<arr.length; i++){51              ListNode node = new ListNode(arr[i]);52              curr.next = node;53              curr = curr.next;54          }55         56         ListNode tmp  = new Solution().insertionSortList(head);57         while(tmp != null){58             System.out.println(tmp.val);59             tmp = tmp.next;60         }61     }62 63 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.