You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现带哨兵节点的泛型双向链表findindexof与makestring方法?

双向链表SLList的makestring与findindexof方法修正实现

原代码问题分析

  • makestring方法:直接返回sentinel.data.toString(),但哨兵节点的data为null(无参构造未赋值),会触发NullPointerException,且未遍历整个链表,无法拼接所有元素。
  • findindexof方法:错误地使用数组下标访问sentinel.data(sentinel.data是单个泛型对象而非数组),属于语法错误;同时未校验索引合法性,也未通过遍历链表定位目标节点。

修正后的方法实现

public class SLList<T> {
    private class IntNode {
        private T data;
        private IntNode previous;
        private IntNode next;

        public IntNode(T data, IntNode previous, IntNode next) {
            this.data = data;
            this.previous = previous;
            this.next = next;
        }

        public IntNode() {
            next = previous = this;
        }
    }

    IntNode sentinel;
    private int length = 0;

    public SLList() {
        sentinel = new IntNode(); // 自引用的哨兵节点
    }

    // 修正后的makestring方法
    public String makestring() {
        if (length == 0) {
            return "[]";
        }
        StringBuilder sb = new StringBuilder("[");
        IntNode current = sentinel.next;
        while (current != sentinel) {
            sb.append(current.data);
            if (current.next != sentinel) {
                sb.append(", ");
            }
            current = current.next;
        }
        sb.append("]");
        return sb.toString();
    }

    // 修正后的findindexof方法
    public T findindexof(int i) {
        if (i < 0 || i >= length) {
            return null;
        }
        IntNode current = sentinel.next;
        for (int j = 0; j < i; j++) {
            current = current.next;
        }
        return current.data;
    }
}

关键实现说明

makestring方法

  1. 空链表处理:先判断length是否为0,直接返回[],避免无效遍历。
  2. 高效拼接:使用StringBuilder而非直接拼接字符串,减少内存开销。
  3. 遍历逻辑:从sentinel.next(链表第一个有效节点)开始遍历,直到current回到哨兵节点(遍历完成),逐个拼接元素。
  4. 格式处理:仅在非尾节点后添加逗号,保证输出格式规范(如[a, b, c])。

findindexof方法

  1. 合法性校验:若索引i小于0或大于等于链表长度,直接返回null,符合"元素不存在则返回null"的要求。
  2. 遍历定位:从表头节点开始,循环i次移动指针,精准定位到第i个节点。
  3. 无修改保证:仅读取节点数据,未改动链表的previous/next指针,满足"不能修改链表"的约束。

内容的提问来源于stack exchange,提问作者Nutnicha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 09:26:13