Reorder List

https://oj.leetcode.com/problems/reorder-list/

Given a singly linked list L: L0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

public void reorderList(ListNode head)


这一题其实就分三步去做。

第一步从中间分开两段,记得如果是长度为偶数则各一半,如果是奇数则左边比右边多一个。

第二步,将后半段reverse,就是普通的reverse list。

第三步,merge list。


下面就根据此把代码放上:

    public void reorderList(ListNode head) {
        if(head == null || head.next == null)
            return;
        ListNode sec_head = dividehelper(head);
        sec_head = reversehelper(sec_head);
        combinehelper(head, sec_head);
    }
    
    public ListNode dividehelper(ListNode head){
        ListNode one_step = head, two_step = head, prev = null;
        while(one_step != null && two_step != null){
            prev = one_step;
            one_step = one_step.next;
            two_step = two_step.next == null ? two_step.next : two_step.next.next;
        }
        prev.next = null;
        return one_step;
    }
    
    public ListNode reversehelper(ListNode head){
        ListNode prev = null, tmp = head, next = tmp.next;
        while(tmp != null){
            next = tmp.next;
            tmp.next = prev;
            prev = tmp;
            tmp = next;
        }
        return prev;
    }
    
    public void combinehelper(ListNode first, ListNode sec){
        while(first != null && sec != null){
            ListNode next_first = first.next;
            ListNode next_sec = sec.next;
            first.next = sec;
            sec.next = next_first;
            first = next_first;
            sec = next_sec;
        }
    }


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值