常考数据结构与算法:单链表的排序
生活随笔
收集整理的這篇文章主要介紹了
常考数据结构与算法:单链表的排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?題目描述
給定一個無序單鏈表,實現單鏈表的排序(按升序排序)。
?
輸入
[1,3,2,4,5]返回值
{1,2,3,4,5} public class SortInListME {public static void main(String[] args) {ListNode l1 = new ListNode(1); // 1,3,2,5,4ListNode l2 = new ListNode(3);ListNode l3 = new ListNode(2);ListNode l4 = new ListNode(5);ListNode l5 = new ListNode(4);l1.next = l2;l2.next = l3;l3.next = l4;l4.next = l5;SortInListME sortInListME = new SortInListME();ListNode resutl = sortInListME.sortInList2(l1);sortInListME.printList(resutl);}public void printList(ListNode head) {ListNode curNode = head;//循環遍歷到尾節點while (curNode != null) {System.out.print(curNode.val + " ");curNode = curNode.next;}System.out.println();}/** 遞歸將鏈表分為兩部分,每部分排好序以后,合并這兩個排好序的鏈表即可 */public ListNode sortInList2 (ListNode head) {// write code hereif (null == head || head.next == null) {return head;}ListNode p1 = head;ListNode p2 = head.next; // 1,3,2,5,4while (p2 != null && p2.next != null) {p1 = p1.next;p2 = p2.next.next;}ListNode p2Head = sortInList2(p1.next);p1.next = null;ListNode p1Head = sortInList2(head);ListNode pre = new ListNode(0);ListNode ansPre = pre;while (p1Head != null && p2Head != null) {if (p1Head.val < p2Head.val) {pre.next = p1Head;p1Head = p1Head.next;} else {pre.next = p2Head;p2Head = p2Head.next;}pre = pre.next;}pre.next = p1Head == null ? p2Head : p1Head;return ansPre.next;}/*** 下面的方法,只能替換節點中的值,不能替換實際的節點* @param head ListNode類 the head node* @return ListNode類*/public ListNode sortInList (ListNode head) {int temp;ListNode curNode = head;while(null != curNode){// 內循環從當前節點的下一個節點開始ListNode nextNode = curNode.next;while(null != nextNode){if(nextNode.val < curNode.val){temp = curNode.val;curNode.val = nextNode.val;nextNode.val = temp;}nextNode = nextNode.next;}curNode = curNode.next;}return head;} }?
總結
以上是生活随笔為你收集整理的常考数据结构与算法:单链表的排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux:进程
- 下一篇: 常考数据结构与算法:单调栈结构