gpt4 book ai didi

java - 为什么我的单链表实现在添加对象后两次给出我的第一个元素?

转载 作者:行者123 更新时间:2023-12-01 16:49:02 25 4
gpt4 key购买 nike

这里我尝试实现“单链表”的基本操作。但只有在这里我只面临一个问题,即添加元素后,即

al.add("Ravi");
al.add("Vijay");
al.add("Sanjay");
al.add("Ajay");

我得到的输出为:
[]--------->对于空链表
[Ravi,Ravi,Vijay,Sanjay,Ajay]------>添加元素后。

class MyLinkedList {
private Node first;
private Node last;
private int count;

public void add(Object ele){
if(first==null){
first=new Node(ele);
last=first;
count++;
}
last.next=new Node(ele);
last=last.next;
count++;
}
public int size(){
return count;
}
public Object get(int index){
if(index>=size())throw new IndexOutOfBoundsException();
Node p=first;
for(int i=0;i<=index;i++){
p=p.next;
}
return p.ele;
}
public void remove(int index){
if(index>=size())throw new IndexOutOfBoundsException();
if(index==0){
first=first.next;
count--;
return;
}
}

@Override
public String toString() {
if(size()==0)return "[]";
Node p=first;
String s="[" + p.ele;
while(p.next!=null){
p=p.next;
s+=","+p.ele;
}
return s + "]";
}

private class Node{
Object ele;
Node next;
Node(Object ele){
this.ele=ele;
}
}

public static void main(String[] args) {
MyLinkedList al=new MyLinkedList();
System.out.println(al);
al.add("Ravi");
al.add("Vijay");
al.add("Sanjay");
al.add("Ajay");
System.out.println(al);

}

}

最佳答案

因为你添加了两次:

    public void **add**(Object ele){
if(first==null){
first=new Node(ele); //First
last=first;
count++;
}
last.next=new Node(ele); //second.
last=last.next;
count++;
}

添加 else 语句:

    public void **add**(Object ele){
if(first==null){
first=new Node(ele);
last=first;
count++;
} else {
last.next=new Node(ele);
last=last.next;
count++;
}
}

关于java - 为什么我的单链表实现在添加对象后两次给出我的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44310117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com