给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4,

思路:1.利用快慢指针找到中间结点,将链表分为前后链表

2.逆转中间结点后面的

3.将逆转后的链表插入前面的链表

重排链表

代码如下:

public void reorderList(ListNode head) {
        if(head == null || head.next == null) return;
        //找到中间结点
        ListNode fast = head;
        ListNode slow = head;
        while(fast!=null&&fast.next!=null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        //标记slow下一个结点,并让slow.next == null
        ListNode tmp = slow.next;
        slow.next = null;
        //逆转slow结点后面的结点
        ListNode s = reverse(tmp);
        ListNode f = head;
        //将逆序后的每一个结点进行插入
        while(s!=null) {
            ListNode cur = s.next;
            s.next = f.next;
            f.next = s;
            f = s.next;
            s = cur;
        }

 

相关文章:

  • 2021-06-10
  • 2022-01-04
  • 2021-10-02
  • 2022-12-23
  • 2022-01-08
  • 2021-10-12
  • 2021-09-18
猜你喜欢
  • 2021-05-29
  • 2021-09-27
  • 2021-11-02
  • 2021-11-28
  • 2022-12-23
相关资源
相似解决方案