「力扣」第 143 题:重排链表(中等)


「力扣」第 143 题:重排链表(中等)

链接:https://leetcode-cn.com/problems/reorder-list

给定一个单链表 LL0→L1→…→L**n-1→Ln ,
将其重新排列后变为: L0→LnL1→Ln-1→L2→L**n-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.

示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

Java 代码:

/**
 * @author liwei
 * @date 18/7/5 上午9:36
 */
public class Solution2 {

    public void reorderList(ListNode head) {
        if (head == null || head.next == null) {
            return;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode anotherHead = slow.next;
        // 步骤1:从中间截断链表
        slow.next = null;
        // 步骤2:反转链表的后半截
        ListNode reverseList = reverseList(anotherHead);
        // 步骤3:合并两个链表
        int k = 0;
        mergeTwoList(head, reverseList, k);
    }

    private ListNode mergeTwoList(ListNode head1, ListNode head2, int k) {
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }
        // k % 2 == 0
        if ((k & 1) == 0) {
            head1.next = mergeTwoList(head1.next, head2, ++k);
            return head1;
        } else {
            head2.next = mergeTwoList(head1, head2.next, ++k);
            return head2;
        }
    }

    private ListNode reverseList(ListNode head) {
        ListNode preNode = null;
        ListNode curNode = head;
        while (curNode != null) {
            ListNode nextNode = curNode.next;
            curNode.next = preNode;
            preNode = curNode;
            curNode = nextNode;
        }
        return preNode;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        Solution2 solution2 = new Solution2();
        ListNode head = new ListNode(nums);
        solution2.reorderList(head);
        System.out.println(head);
    }
}

文章作者: liweiwei1419
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 liweiwei1419 !
评论
 上一篇
「力扣」第 146 题:LRU 缓存机制(中等) 「力扣」第 146 题:LRU 缓存机制(中等)
「力扣」第 146 题:LRU 缓存机制(中等) 链接 题解链接 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key)
下一篇 
「力扣」第 142 题:环形链表 II(中等) 「力扣」第 142 题:环形链表 II(中等)
「力扣」第 142 题:环形链表 II(中等)链接:https://leetcode-cn.com/problems/linked-list-cycle-ii 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
  目录