C#自定义LinkedList的Get方法取值异常问题求助
问题分析与修复方案
你的Get方法测试失败,核心原因有两点:
1. Add方法逻辑与测试预期不匹配
你明确提到LinkedList实现了头部添加功能,但测试用例是按照尾部添加的顺序编写的:
- 调用
Add(42)、Add(43)、Add(44)时,头部添加会让链表顺序变为44 → 43 → 42(新元素始终插在链表头部) - 但测试预期结果是
[42,43,44],这是尾部添加的顺序,自然会导致Get返回值与预期不符,测试失败。
修复方式二选一:
- 改为尾部添加:调整Add方法实现,将新节点追加到链表末尾:
public void Add(T value) { Node<T> newNode = new Node<T> { value = value }; if (start == null) { start = newNode; return; } Node<T> current = start; while (current.next != null) { current = current.next; } current.next = newNode; }
- 保留头部添加:修改测试用例的预期结果为
[44,43,42],同时建议将该方法重命名为AddFirst,避免语义混淆。
2. Get方法缺少索引有效性检查
原Get方法未处理索引越界场景:
- 当
index大于等于链表长度时,循环会让previous变为null,访问previous.value会直接抛出NullReferenceException - 也未校验
index为负数的非法输入
修复后的Get方法:
public T Get(int index) { if (start == null) { throw new InvalidOperationException("链表为空"); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), "索引不能为负数"); } Node<T> current = start; int currentIndex = 0; while (current != null) { if (currentIndex == index) { return current.value; } current = current.next; currentIndex++; } // 循环结束未找到对应索引,说明越界 throw new ArgumentOutOfRangeException(nameof(index), "索引超出链表范围"); }
额外优化建议
- 给LinkedList类添加
Count属性,实时记录链表长度,可在Get方法中快速判断索引是否越界,提升性能 - 统一使用.NET标准异常类型(如
InvalidOperationException代替通用Exception),符合编码规范
内容的提问来源于stack exchange,提问作者Martín Zuluaga
相关产品推荐
相关产品推荐

