资讯专栏INFORMATION COLUMN

[LeetCode] 143. Reorder List

miracledan / 2109人阅读

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

</>复制代码

  1. class Solution {
  2. public void reorderList(ListNode head) {
  3. if (head == null || head.next == null) return;
  4. ListNode fast = head, slow = head.next, split = head;
  5. while (fast != null && fast.next != null) {
  6. split = slow; //to split slow to next half
  7. fast = fast.next.next;
  8. slow = slow.next;
  9. }
  10. //1 2 3 4 5
  11. //3, 3, 2 (fast, slow, split)
  12. //5, 4, 3 (fast, slow, split)
  13. //1 2 3 4
  14. //3, 3, 2
  15. split.next = null;
  16. ListNode l2 = reverse(slow);
  17. ListNode l1 = head;
  18. while (l2 != null) {
  19. ListNode n1 = l1.next;
  20. ListNode n2 = l2.next;
  21. l1.next = l2;
  22. l2.next = n1;
  23. l1 = n1;
  24. l2 = n2;
  25. }
  26. return;
  27. }
  28. private ListNode reverse(ListNode node) {
  29. ListNode pre = null;
  30. while (node != null) {
  31. ListNode next = node.next;
  32. node.next = pre;
  33. pre = node;
  34. node = next;
  35. }
  36. return pre;
  37. }
  38. }

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

转载请注明本文地址: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元查看
<