链表插入排序 lintcode
2016-10-18 10:10
246 查看
链表插入排序
难度系数 容易 通过率 31%描述
笔记
数据
评测
用插入排序对链表排序
您在真实的面试中是否遇到过这个题?
Yes
样例
Given
1->3->2->0->null,
return
0->1->2->3->null
package tju.cs.bigdata.chc;
public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
public ListNode createList(String s){
ListNode res = new ListNode(-1);
String[] strings = s.split("->");
ListNode cur = res;
for(String st : strings){
if(!st.equals("null"))cur.next = new ListNode(Integer.parseInt(st));
cur = cur.next;
}
return res.next;
}
public void printList(ListNode l){
ListNode cur = l;
if(l == null)return;
while(cur != null){
System.out.print(cur.val + " ");
cur = cur.next;
}
}
}
package tju.cs.bigdata.chc; public class InsertionSortList { public ListNode insertionSortList(ListNode head) { // write your code here if(head == null || head.next == null){ return head; } ListNode res = new ListNode(-1); ListNode cur = head; ListNode curtmp = res; while(cur != null){ curtmp = res; while(curtmp.next != null && curtmp.next.val <= cur.val){ curtmp = curtmp.next; } // curtmp.printList(curtmp); // cur.printList(cur); ListNode l = cur.next; cur.next = curtmp.next; curtmp.next = cur; cur = l; // if(cur != null)cur.printList(cur); // curtmp.printList(curtmp); } return res.next; } public static void main(String[] args){ String string = "1->3->2->0->null"; ListNode res = new ListNode(-1).createList(string); res.printList(res); InsertionSortList insertionSortList = new InsertionSortList(); ListNode res1 = insertionSortList.insertionSortList(res); res1.printList(res1); } }
相关文章推荐
- lintcode-链表插入排序
- 链表插入排序-LintCode
- 链表插入排序-LintCode
- 【LintCode 简单】173. 链表插入排序
- LintCode-链表插入排序
- LintCode-链表插入排序
- lintcode 173 链表插入排序
- LintCode(E) 链表插入排序
- [LintCode] 链表插入排序
- LintCode 链表插入排序
- 【lintcode】——链表插入排序-Insertion Sort List
- LintCode 链表插入排序
- Lintcode 173.链表插入排序
- lintcode——链表插入排序
- 173链表插入排序
- LintCode : 链表排序
- 插入排序之链表实现
- 单链表---直接插入排序
- lintcode,合并两个排序链表
- 链表排序(冒泡、选择、插入、快排、归并、希尔、堆排序)