[Leetcode学习-java]Reorder List(重排序链表)

问题:

难度:medium

说明:

输入一个链表,要求他的排序出现这样的变化,L(0) > L(1) > L(2) > L(3)......   变成 L(0) > L(N - 1) > L(1) > L(N - 2) > L(2) ...... > L(N - i) > L(i)。

问题链接:https://leetcode.com/problems/reorder-list/

相关问题:

Reverse Words in a String(将字符串单词顺序反转):https://blog.csdn.net/qq_28033719/article/details/107386312

Reverse Linked List(反转链表):https://blog.csdn.net/qq_28033719/article/details/105010066

 

输入案例:

Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

我的代码:

其实就基于循环和下一个的操作处理就行,什么时候才用下一个节点,要什么算是处理完毕,同时面向数据编程,继续使用数组省事。

class Solution {
    private static int[] arr = new int[(int)Math.pow(2, 15)]; // 面向数据编程
    public void reorderList(ListNode head) {
        int index = 0;
        ListNode temp = null;
        if(head != null) temp = head.next;
        while(head != null) { // 把值放数组内
            arr[index ++] = head.val; head = head.next;
        }
        int e = index >> 1; // 只取一半
        for(int i = 1;i <= e;i ++) {
            temp.val = arr[index - i];
            temp = temp.next;
            if(temp != null) { // 什么时候用下一个节点
                temp.val = arr[i];
                temp = temp.next;
            }
        }
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值