链表排序

来源:互联网 发布:机器人离线编程培训班 编辑:程序博客网 时间:2024/06/06 12:26

<p>对链表进行合并算法排序,基本思路和merge算法一下。</p><p>一下是Java实现:</p><div></div>
public class ListNode{int val;ListNode next;ListNode(int val){this(val, null);}ListNode(int val, ListNode next){this.val = val;this.next = next;}}public class Util{public static void printList(ListNode head){ListNode node = head;StringBuilder builder = new StringBuilder();while(node != null){builder.append(node.val + " ");node = node.next;}System.out.println(builder.toString().trim());}}public class MergeSortList{public static void main(String[] args){int[] arr = {1,3,3,1,3,1,3,3,2,3,2,2,1,1,2,3};ListNode head = null, tail = null;for(int i = 0; i < arr.length; i++){if(head == null) {head = new ListNode(arr[i]);tail = head;}else{tail.next = new ListNode(arr[i]);tail = tail.next;}}Util.printList(head);ListNode m = new MergeSortList().sort(head);Util.printList(m);}public ListNode sort(ListNode head){if(head == null || head.next == null) return head;ListNode hnode = head;ListNode lnode = split(hnode);hnode = sort(hnode);lnode = sort(lnode);ListNode m = merge(hnode, lnode);return m;}/** * Merge to sorted list * */public ListNode merge(ListNode alist, ListNode blist){if(alist == null) return blist;if(blist == null) return alist;ListNode rvl = null;ListNode tmp = null;if(alist.val <= blist.val){tmp = alist.next;rvl = alist;rvl.next = merge(tmp, blist);}else{tmp = blist.next;rvl = blist;rvl.next = merge(alist, tmp);}return rvl;}public ListNode split(ListNode head){ListNode fast;ListNode slow;if(null == head || null == head.next){return null;}slow = head;fast = head.next;while(fast != null){fast = fast.next;if(fast != null){slow = slow.next;fast = fast.next;}}ListNode low = slow.next;slow.next = null;return low;}}

输出结果:

1 3 3 1 3 1 3 3 2 3 2 2 1 1 2 3
1 1 1 1 1 2 2 2 2 3 3 3 3 3 3 3

0 0
原创粉丝点击