当前位置:   article > 正文

LeetCode:reorder-list链表重排序_将给定的单链表: 重新排序为:

将给定的单链表: 重新排序为:

题目描述

 

将给定的单链表L: L 0→L 1→…→L n-1→L n,

重新排序为: L 0→L n →L 1→L n-1→L 2→L n-2→…

要求使用原地算法,并且不改变节点的值

例如:

对于给定的单链表{1,2,3,4},将其重新排序为{1,4,2,3}.

Given a singly linked list L: L 0→L 1→…→L n-1→L n,

reorder it to: L 0→L n →L 1→L n-1→L 2→L n-2→…

You must do this in-place without altering the nodes' values.

For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.

-------------------------------------------------------------------------------------------------------------------

解题思路:

(1)利用快慢指针找到链表中间结点

(2)以中间节点为准将链表拆分成两半,反转中间结点后的后半部分链表

(3)合并前半部分链表和反转后的后半部分链表

Java代码实现

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) {
  7. * val = x;
  8. * next = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. public void reorderList(ListNode head) {
  14. if(head == null || head.next == null)
  15. return;
  16. //快慢指针寻找中间结点
  17. ListNode slow = head, fast = head;
  18. while(fast.next != null && fast.next.next != null){
  19. fast = fast.next.next;
  20. slow = slow.next;
  21. }
  22. ListNode after = slow.next;
  23. //断链,拆分链表
  24. slow.next = null;
  25. ListNode pre = null;
  26. //反转链表
  27. while(after != null){
  28. ListNode tmp = after.next;
  29. after.next = pre;
  30. pre = after;
  31. after = tmp;
  32. }
  33. //合并链表
  34. ListNode first = head;
  35. after = pre;
  36. while(first != null && after != null){
  37. ListNode first_tmp = first.next;
  38. ListNode after_tmp = after.next;
  39. first.next = after;
  40. first = first_tmp;
  41. after.next = first;
  42. after = after_tmp;
  43. }
  44. }
  45. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/226653
推荐阅读
相关标签
  

闽ICP备14008679号