Reorder List

给定一个单链表,将其重新排序,将第n个节点插入到第0个和第1个节点之间,以此类推,例如给定{1,2,3,4},排序后为{1,4,2,3}。解法使用快慢指针切分链表,再将后半部分逆序,最后拼接。" 124223506,11957480,"ES6字符串新方法与数据类型:startwith(), endswith(), trim(), Map, Symbol及Class继承
摘要由CSDN通过智能技术生成

Description:

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

问题描述:

给一条单链表,有n+1个结点,将第n个结点插入到第0个结点与第1个结点之间,将第n-1个结点插入到第1个结点与第2个结点之间,依次类推。

Ex:

Given {1,2,3,4}, reorder it to {1,4,2,3}.

解法一:

思路:

看到这种处理最后一个元素(第n个结点)开始的操作,本能想到用快慢指针,但是这种插入操作,最多只能插入链表总长度一半的元素。所以,主要的步骤分三步处理,先将整条链表切分成前半部分和后半部分,第二步,将后半部分链表逆序(非常重要,又出现了,一定要背下来)。第三步,完成逆序后的后半部分链表和前半部分的拼接操作。

Code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        if(head == null || head.next == null)
            return;
        //Step1: Cut the list to two halves
        //prev will be the tail of the 1st half
        //slow will be the head of the 2nd half
        ListNode prev = null;
        ListNode slow = head, fast = head,l1 =head;

        while(fast != null && fast.next != null){
            prev = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        prev.next = null;

        //Step2: reverse the 2nd half
        ListNode l2 = reverse(slow);

        //Step3: merge the two halves
        merge(l1,l2);
    }
    private ListNode reverse(ListNode head){
        ListNode prev = null, curr = head, next =null; 
        while(curr != null){
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
    private void merge(ListNode l1, ListNode l2){
        while(l1 != null){
            ListNode n1 = l1.next, n2 = l2.next;
            l1.next = l2;

            if(n1 == null)
                break;

            l2.next = n1;

            l1 = n1;
            l2 = n2;
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值