Insertion Sort List
2014-11-24 23:02
239 查看
Insertion Sort List
Sort a linked list using insertion sort.这道题用两个链表做的,这样方便一点。还有新链表头结点我没有存放内容,这样也比较方便,后面返回head1.next就好了
/** * 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) { ListNode head1 = new ListNode(0); if(null == head || null == head.next) return head; else{ ListNode temp = new ListNode(0); temp.val = head.val; temp.next = null; head1.next = temp;//用一个新链表 ListNode ptr = head.next; while(ptr != null){ //遍历原来的链表,插入到新链表中 temp = head1.next; ListNode tempPre = head1; //temp前面的节点 while(temp != null){ if(temp.val > ptr.val){ //在temp前面插入结点 ListNode nodeAdd = new ListNode(0); nodeAdd.val = ptr.val; nodeAdd.next = temp; tempPre.next = nodeAdd; break; //插入完成,跳出循环 } temp = temp.next; tempPre = tempPre.next; } if(null == temp){ //在新链表添加节点 ListNode nodeAdd = new ListNode(0); nodeAdd.val = ptr.val; nodeAdd.next = null; tempPre.next = nodeAdd; } ptr = ptr.next; } } return head1.next; } }
相关文章推荐
- [LintCode] Insertion Sort List
- Leetcode: Insertion Sort List
- leetcode InsertionSort list
- Insertion Sort List,Min Stack,Reorder List
- LeetCode - Insertion Sort List
- Insertion Sort List and Binary Tree Paths
- [leetcode] Insertion Sort List
- leetcode 之 Insertion Sort List
- Insertion Sort List
- leetcode Insertion Sort List
- 【leetcode】Insertion Sort List
- LeetCode Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- LeetCode: Insertion Sort List
- [LeetCode] Insertion Sort List 链表插入排序
- [C++]LeetCode: 126 Insertion Sort List (插入排序链表)
- LeetCode---Insertion Sort List
- LeetCode:Insertion Sort List
- LeetCode--insertion-sort-list