一、题目内容

image.png

二、题解

解法1:

思路

快慢指针找中点后逆序后半部分,拼接链表

代码

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