LeetCode 链表的插入排序
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 链表的插入排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Sort a linked list using insertion sort
創建一個新的鏈表,將舊鏈表的節點插入到正確的位置
package cn.edu.algorithm.huawei;public class Solution {public ListNode insertionSortList(ListNode head) {//啞節點ListNode dumy = new ListNode(Integer.MIN_VALUE);ListNode cur = head;ListNode pre = dumy;while (cur != null) {//保存當前節點下一個節點ListNode next = cur.next;pre = dumy;//尋找當前節點正確位置的一個節點while (pre.next != null && pre.next.val < cur.val) {pre = pre.next;}//將當前節點加入新鏈表中cur.next = pre.next;//指向插入位置后面的節點ListNode test = cur.next;pre.next = cur;//處理下一個節點cur = next;}return dumy.next;}public static void main(String[] args) {ListNode head = new ListNode(2);head.next = new ListNode(1);Solution solution = new Solution();ListNode list = solution.insertionSortList(head);while (list != null) {System.out.println(list.val);list = list.next;}} }class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}@Overridepublic String toString() {return val + "";} }?
轉載于:https://www.cnblogs.com/googlemeoften/p/5818841.html
總結
以上是生活随笔為你收集整理的LeetCode 链表的插入排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 创建DataTable并把列默认值
- 下一篇: Spring的国际化(转载)