如何实现带哨兵节点的泛型双向链表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方法
- 空链表处理:先判断
length是否为0,直接返回[],避免无效遍历。 - 高效拼接:使用
StringBuilder而非直接拼接字符串,减少内存开销。 - 遍历逻辑:从
sentinel.next(链表第一个有效节点)开始遍历,直到current回到哨兵节点(遍历完成),逐个拼接元素。 - 格式处理:仅在非尾节点后添加逗号,保证输出格式规范(如
[a, b, c])。
findindexof方法
- 合法性校验:若索引
i小于0或大于等于链表长度,直接返回null,符合"元素不存在则返回null"的要求。 - 遍历定位:从表头节点开始,循环
i次移动指针,精准定位到第i个节点。 - 无修改保证:仅读取节点数据,未改动链表的
previous/next指针,满足"不能修改链表"的约束。
内容的提问来源于stack exchange,提问作者Nutnicha
相关产品推荐
相关产品推荐

