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→…

Bertha 。 2022-05-26 04:25 302阅读 0赞

题目描述

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. /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
  2. public class Solution {
  3. public void reorderList(ListNode head) {
  4. if(head == null || head.next == null || head.next.next == null)
  5. return;
  6. ListNode slow = head;
  7. ListNode fast = head;
  8. //快慢指针找到中间结点
  9. while(fast != null && fast.next != null && fast.next.next != null){
  10. slow = slow.next;
  11. fast = fast.next.next;
  12. }
  13. //断开链表,fast指向后半部分链表,head仍然是头结点,之前前半部分链表
  14. fast = slow;
  15. slow = slow.next;
  16. fast.next = null;
  17. //翻转链表
  18. ListNode lastHead = ReverseNode(slow);
  19. ListNode newHead = head;
  20. head = head.next;
  21. //合并链表
  22. while(head != null && lastHead != null){
  23. newHead.next = lastHead;
  24. lastHead = lastHead.next;
  25. newHead = newHead.next;
  26. newHead.next = head;
  27. head = head.next;
  28. newHead = newHead.next;
  29. }
  30. if(head != null)
  31. newHead.next = head;
  32. if(lastHead != null)
  33. newHead.next = lastHead;
  34. }
  35. private ListNode ReverseNode(ListNode head){
  36. ListNode prev = null;
  37. ListNode curr = head;
  38. while(curr != null && curr.next != null){
  39. ListNode next = curr.next;
  40. curr.next = prev;
  41. prev = curr;
  42. curr = next;
  43. }
  44. curr.next = prev;
  45. return curr;
  46. }
  47. }

发表评论

表情:
评论列表 (有 0 条评论,302人围观)

还没有评论,来说两句吧...

相关阅读

    相关 L1-009. N个数求和

    本题的要求很简单,就是求N个数字的和。麻烦的是,这些数字是以有理数“分子/分母”的形式给出的,你输出的和也必须是有理数的形式。 输入格式: 输入第一行给出一个正整数N(<=

    相关 L1-009 N个数求和

    L1-009 N个数求和 (20 分) 本题的要求很简单,就是求`N`个数字的和。麻烦的是,这些数字是以有理数`分子/分母`的形式给出的,你输出的和也必须是有理数的形式。