Java for LeetCode (163)

本文介绍了一种使用Java实现的重排链表算法解决方案。该算法采用线性表加双指针的方法来解决LeetCode第143题的问题。通过遍历链表将节点存储到数组中,再利用双指针技术重新排列链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

是差点运气,可我一直在努力!

当前进程:

  • 开始时间:2020.10.20
  • 结束时间:undefined

注意:
从今天开始,将使用Java语言,继续进行刷题计划,原计划的JavaScript / TypeScript语言刷题之路暂时一段落。

原仓库:https://github.com/Cundefined/JavaScript-or-TypeScript-for-LeetCode

GitHub仓库:https://github.com/Cundefined/Java-for-LeetCode

1、题目要求

( LeetCode – 第143题 ) 重排链表

2、解题思路

线性表+双指针

3、Java Solution

/**
 * 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) {
            return;
        }

        List<ListNode> list = new ArrayList<ListNode>();

        //遍历链表,把所有节点加入数组
        ListNode cur = head;
        while(cur != null) {
            list.add(cur);
            cur = cur.next;
        }

        //双指针遍历数组,重新排列链表
        int l = 0;
        int r = list.size() - 1;
        while(l < r) {
            list.get(l).next = list.get(r);
            l++;
            //偶数个节点会出现l==r情况还继续连接,此时应该跳出循环
            if(l == r) {
                break;
            }
            list.get(r).next = list.get(l);
            r--;
        }
        list.get(l).next = null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值