没有返回值的add递归,老师帮忙看看是否正确?
public void add(LinkedListR listR, int index, E e) {
throw new IllegalArgumentException("Add failed. Illegal index"); }
if (index == 0) {
listR.head=new Node(e,listR.head);
} else {
Node removed = listR.head;
listR.head=listR.head.next;
add(listR, index - 1, e);
removed.next = listR.head;
listR.head=removed;
}
size++;
}
14
收起
正在回答 回答被采纳积分+1
1回答
liuyubobobo
2022-07-21 03:40:58
是有问题的。
下面的代码的 add 使用了你的逻辑。测试的 main 函数中,你会看到,当最后一个添加操作在 index = 2 的位置添加了 666 以后,原来的链表 index = 2 位置后面的部分丢失了。
即:0->1->2->3->4->null 在 index = 2 添加 666 以后,应该是:
0->1->666->2->3->4->null
你的逻辑的得到结果是:
0->1->666->null
另外,你的程序中的 size 也会多次添加,在同样的这份程序中,一共添加了 6 个元素,你的程序最终得到的 size 是 18。
可以自己仔细调试一下,理解一下,为什么会这样?
public class LinkedList<E> {
private class Node{
public E e;
public Node next;
public Node(E e, Node next){
this.e = e;
this.next = next;
}
public Node(E e){
this(e, null);
}
public Node(){
this(null, null);
}
@Override
public String toString(){
return e.toString();
}
}
private Node head;
private int size;
public LinkedList(){
head = null;
size = 0;
}
public void add(LinkedList<E> listR, int index, E e){
if(index < 0 || index > size)
throw new IllegalArgumentException("Add failed. Illegal index.");
if(index == 0)
listR.head = new Node(e);
else{
Node removed = listR.head;
listR.head=listR.head.next;
add(listR, index - 1, e);
removed.next = listR.head;
listR.head=removed;
}
size ++;
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
for(Node cur = head ; cur != null ; cur = cur.next)
res.append(cur + "->");
res.append("NULL");
return res.toString();
}
public static void main(String[] args) {
LinkedList<Integer> linkedList = new LinkedList<>();
for(int i = 0 ; i < 5 ; i ++){
linkedList.add(linkedList, i, i);
System.out.println(linkedList);
}
linkedList.add(linkedList, 2, 666);
System.out.println(linkedList); // 这个输出是错的
System.out.println(linkedList.size); // 这个输出也是错的
}
}继续加油!:)
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星