【发布时间】:2023-03-12 10:24:01
【问题描述】:
我目前正在尝试复习 ADT 实现,特别是链接列表的实现(我正在使用 Java 5 来执行此操作)。
我有两个问题:
(1) 我为 add(i, x) 编写的这个实现是否正确且高效?
public void add(int i, Object x) { // Possible Cases: // // 1. The list is non-empty, but the requested index is out of // range (it must be from 0 to size(), inclusive) // // 2. The list itself is empty, which will only work if i = 0 // // This implementation of add(i, x) relies on finding the node just before // the requested index i. // These will be used to traverse the list Node currentNode = head; int indexCounter = 0; // This will be used to mark the node before the requested index node int targetIndex = i - 1; // This is the new node to be inserted in the list Node newNode = new Node(x); if (currentNode != null) { while (indexCounter < targetIndex && currentNode.getNext() != null) { indexCounter++; currentNode = currentNode.getNext(); } if (indexCounter == targetIndex) { newNode.setNext(currentNode.getNext()); currentNode.setNext(newNode); } else if (i == 0) { newNode.setNext(head); head = newNode; } } else if (i == 0) { head = newNode; } }
(2) 我发现这种方法很难实现。老实说,我花了好几天的时间。这很难承认,因为我喜欢编程,并且认为自己在几种语言和平台方面处于中级水平。我从 13 岁起就开始编程(Apple IIc 上的 Applesoft BASIC!),并获得了计算机科学学位。我目前是一名软件测试员,并计划在某个时候成为一名开发人员。所以我的问题的第二部分是:我是在自欺欺人地认为这是我擅长的工作类型,还是几乎每个人都觉得这种问题具有挑战性?有些事情告诉我,即使是经验丰富的开发人员,在面临实施这种方法时也会发现它具有挑战性。
感谢您对第二部分的反馈和建议。
【问题讨论】:
-
@dvanaria:我觉得这个问题更适合codereview.stackexchange.com。
-
好的,谢谢,我从未听说过 codereview.stackexchange,它听起来确实是一个更好的地方。我现在会考虑把它移过来。
-
我的问题的第二部分仍然正确,还是对stackoverflow不够客观?
标签: java data-structures linked-list implementation abstract-data-type