资讯专栏INFORMATION COLUMN

[LeetCode] 143. Reorder List

miracledan / 2034人阅读

Problem

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You may not modify the values in the list"s nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

Solution
class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null) return;
        ListNode fast = head, slow = head.next, split = head;
        while (fast != null && fast.next != null) {
            split = slow; //to split slow to next half
            fast = fast.next.next;
            slow = slow.next;
        }
        //1 2 3 4 5
        //3, 3, 2 (fast, slow, split)
        //5, 4, 3 (fast, slow, split)
        
        //1 2 3 4
        //3, 3, 2
        split.next = null;
        ListNode l2 = reverse(slow);
        ListNode l1 = head;
        while (l2 != null) {
            ListNode n1 = l1.next;
            ListNode n2 = l2.next;
            l1.next = l2;
            l2.next = n1;
            l1 = n1;
            l2 = n2;
        }
        return;
    }
    private ListNode reverse(ListNode node) {
        ListNode pre = null;
        while (node != null) {
            ListNode next = node.next;
            node.next = pre;
            pre = node;
            node = next;
        }
        return pre;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77356.html

相关文章

  • [Leetcode] Reorder List 链表重新排序

    摘要:要找到后半部分的起点,就是用快慢指针。不过该题我们不能直接拿到中间,而是要拿到中间的前一个节点,这样才能把第一个子链表的末尾置为空,这里的技巧就是快慢指针循环的条件是。注意因为不能有额外空间,我们最好用迭代的方法反转链表。 Reorder List Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→...

    hufeng 评论0 收藏0
  • Leetcode PHP题解--D54 937. Reorder Log Files

    摘要:题目链接题目分析给定一个数组,每一个元素是一条日志。剩余部分为全为小写字母的字符串称为字符日志或全为数字的字符串称为数字日志。给定的数组中确定会至少有一个字母。遍历完成后,对字符日志进行排序。在其后拼接数字日志数组,并返回即可。 D54 937. Reorder Log Files 题目链接 937. Reorder Log Files 题目分析 给定一个数组,每一个元素是一条日志。 ...

    hot_pot_Leo 评论0 收藏0
  • [LeetCode] 937. Reorder Log Files

    Problem You have an array of logs. Each log is a space delimited string of words. For each log, the first word in each log is an alphanumeric identifier. Then, either: Each word after the identifier...

    nemo 评论0 收藏0
  • [LintCode] Reorder List [链表综合题型]

    摘要:链表题目的集合双指针法找中点,分割,合并,翻转,排序。主函数对于长度为或的链表,返回找到中点分割链表并翻转后半段为与前半段合并。当移动到最后一个元素,正好移动到整个链表的头部。 Problem Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln reorder it to: L0 → Ln → L1 → Ln-1 → L2 → L...

    王军 评论0 收藏0
  • [LeetCode] 280. Wiggle Sort

    Problem Given an unsorted array nums, reorder it in-place such that nums[0] = nums[2] nums[i-1]) swap(nums, i, i-1); } } } private void swap(int[] nums, int i, int j) { ...

    archieyang 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<