链表的升级实战

   /**
     * 单链表反转
     */
    public static ListNode reverse(ListNode head){
        ListNode pre = null; //当前节点的前一个节点
        ListNode next = null;//当前节点的下一个节点 
        
        while(head != null) {
            next = head.next; //保存下一个节点
            head.next = pre; //重置next
            pre = head; //保存当前节点
            head = next; //重置当前节点
        }
        return pre;
    }
/** * 取中间值 */ public static ListNode getMid(ListNode head) { ListNode fast = head; ListNode slow = head; while(fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } /** * 拆分链表 */ public static ListNode[] getLists(ListNode head) { ListNode head1 = null; ListNode head2 = null; ListNode cur1 = null; ListNode cur2 = null; int count = 0; while(head!=null) { if(count%2 == 0) { if(cur1 != null) { cur1.next = head; cur1 = cur1.next; }else { cur1 = head; head1 = cur1; } }else { if(cur2 != null) { cur2.next = head; cur2 = cur2.next; }else { cur2 = head; head2 = cur2; } } head = head.next; count++; } if (cur1 != null && cur2 != null) { cur1.next = null; cur2.next = null; } if(cur1 != null){ cur1.next = null; } if(cur2 != null) { cur2.next = null; } ListNode[] listNodes = new ListNode[]{head1, head2}; return listNodes; } /** * 归并排序链表 */ public static ListNode sortList(ListNode head){ if(head == null ||head.next == null) { return head; } ListNode mid = getMid(head); ListNode right = mid.next; mid.next = null;//咬断链表 ListNode node = mergeTwoListNode(sortList(head), sortList(right)); return node; } /** * 合并两个链表 * @param head1 * @param head2 */ public static ListNode mergeTwoListNode(ListNode head1, ListNode head2) { if(head1 == null || head2 == null) { return head1 == null? head2 : head1; } ListNode head = null; if(head1.value > head2.value) { head = head2; head.next = mergeTwoListNode(head1, head2.next); }else { head = head1; head.next = mergeTwoListNode(head1.next, head2); } return head; } public static void main(String[] args) { ListNode head = new ListNode(1); ListNode node2 = new ListNode(8); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(6); ListNode node5 = new ListNode(5); ListNode node6 = new ListNode(4); ListNode node7 = new ListNode(7); ListNode node8 = new ListNode(2); ListNode node9 = new ListNode(9); head.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; node5.next = node6; node6.next = node7; node7.next = node8; node8.next = node9; Mylist.traverse(head); ListNode[] nodes = getLists(head); ListNode head1 = nodes[0]; ListNode head2 = nodes[1]; head2 = reverse(head2); head = mergeTwoListNode(head1, head2); Mylist.traverse(head); Mylist.traverse(sortList(head)); }

 

posted @ 2019-03-21 10:32  提拉没有米苏  阅读(199)  评论(0编辑  收藏  举报