2022-7-30 剑指offer-链表-递归

剑指 Offer II 026. 重排链表

难度中等

给定一个单链表 L 的头节点 head ,单链表 L 表示为:

 L0 → L1 → … → Ln-1 → Ln 
请将其重新排列后变为:

L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        if (head==null||head.next==null||head.next.next==null) return;
        ListNode nextNode=head.next;
        ListNode temp=head;
        while (temp.next.next!=null){
            temp=temp.next;
        }
        ListNode last=temp.next;
        temp.next=null;
        head.next=last;
        last.next=nextNode;
        reorderList(nextNode);
    }
}

思路:递归实现,先找到最后的节点,接在第一个节点后面,问题就可以转化为减少长度的子问题。

posted on 2022-07-30 10:40  阿ming  阅读(17)  评论(0)    收藏  举报

导航