我想在 Java 中添加一个方法 add(int index, E element)
,该方法在列表中的指定索引处插入指定元素,并移动当前位于该位置的元素(如果有) )以及右侧的任何后续元素(为其索引加一)。但我猜想 for 循环中代码中的索引有问题。有什么解决办法吗?
public class SingleLinkedList<E> implements ISingleLinkedList<E> {
Node head;
int size = 0;
@Override
public void add(int index, E element) throws IndexOutOfBoundsException {
Node newNode = new Node(element);
if(head == null && index == 0) {
head = newNode;
}
else if (index == 0 && head != null) {
Node tempNode = new Node(element);
tempNode.setmNextNode(head);
head = tempNode;
}
else {
Node tempNode = head;
for(int i = 1; i<index; i++) {
tempNode = tempNode.getmNextNode();
}
/**Node newNode = new Node(element);**/
newNode.setmNextNode(tempNode);
tempNode.setmNextNode(newNode);
}
size++;
}
}
我的 Node 类代码是:
public class Node<E> {
private E mElement;
private Node<E> mNextNode;
Node(E data) {
this.setmElement(data);
}
public E getmElement() {
return this.mElement;
}
public void setmElement(E element) {
this.mElement = element;
}
public Node<E> getmNextNode()
{
return this.mNextNode;
}
public void setmNextNode(Node<E> node)
{
this.mNextNode = node;
}
问题是我的 JUnit 测试在添加此方法时失败,并且我不知道还需要添加什么才能通过测试。
@Test
public void testAddWithIndexesToListWith5Elements() {
int listSize = 5;
// First create an ArrayList with string elements that constitutes the test data
ArrayList<Object> arrayOfTestData = generateArrayOfTestData(listSize);
// Then create a single linked list consisting of the elements of the ArrayList
ISingleLinkedList<Object> sll = createSingleLinkedListOfTestData(arrayOfTestData);
// Add new elements first, in the middle and last to the ArrayList of test data
// and the single linked list
try {
arrayOfTestData.add(0, 42);
arrayOfTestData.add(3, "addedElement1");
arrayOfTestData.add(7, "addedElement2");
sll.add(0, 42);
sll.add(3, "addedElement1");
sll.add(7, "addedElement2");
}
catch (Exception e) {
fail("testAddWithIndexesToListWith5Elements - add() method failed");
}
// Check that the contents are equal
for (int i = 0; i < sll.size(); i++) {
assertEquals(arrayOfTestData.get(i), sll.get(i));
}
}
最佳答案
newNode.setmNextNode(tempNode);
tempNode.setmNextNode(newNode);
这只会创建一个循环。看起来您的 newNode
应该指向 tempNode.getmNextNode()
或类似的东西。
关于java - 添加方法java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60140372/