当前位置:   article > 正文

LeetCode-reorder-list

LeetCode-reorder-list

Given a singly linked list LL 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. * 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. ListNode slow=head;
  17. ListNode fast=head;
  18. while(fast.next!=null&&fast.next.next!=null){
  19. slow=slow.next;
  20. fast=fast.next.next;
  21. }
  22. ListNode preMiddle=slow;
  23. ListNode precurr=slow.next;
  24. while(precurr.next!=null){
  25. ListNode current=precurr.next;
  26. precurr.next=current.next;
  27. current.next=preMiddle.next;
  28. preMiddle.next=current;
  29. }
  30. slow=head;
  31. fast=preMiddle.next;
  32. while(slow!=preMiddle){
  33. preMiddle.next=fast.next;
  34. fast.next=slow.next;
  35. slow.next=fast;
  36. slow=fast.next;
  37. fast=preMiddle.next;
  38. }
  39. }
  40. }

 

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

闽ICP备14008679号