offer2-26


给定一个单链表 L 的头节点 head ,单链表 L 表示为:

L0 → L1 → … → Ln-1 → Ln
请将其重新排列后变为:

L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

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

示例 1:

img

输入: head = [1,2,3,4]
输出: [1,4,2,3]

示例 2:

img

输入: head = [1,2,3,4,5]
输出: [1,5,2,4,3]

提示:

  • 链表的长度范围为 [1, 5 * 104]
  • 1 <= node.val <= 1000

//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null) {
            return;
        }

        List<ListNode> nodeList = new ArrayList<>();
        ListNode temp = head;

        while (temp != null) {
            nodeList.add(temp);
            temp = temp.next;
        }

        doOrder(head, 0, nodeList);
    }

    ListNode doOrder(ListNode curNode, int index, List<ListNode> nodeList) {
        if ((nodeList.size() % 2 == 0 && nodeList.size() / 2 == index + 1) || (nodeList.size() % 2 == 1 && nodeList.size() / 2 == index)) {
            ListNode last = nodeList.get(nodeList.size() - 1 - index);
            last.next = null;
            return curNode;
        }

        ListNode nextNode = doOrder(curNode.next, index + 1, nodeList);
        ListNode second = nodeList.get(nodeList.size() - 1 - index);
        curNode.next = second;
        second.next = nextNode;
        return curNode;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !