gpt4 book ai didi

java - java中的数据结构

转载 作者:行者123 更新时间:2023-11-30 11:29:46 25 4
gpt4 key购买 nike

我创建此代码是为了将客户对象添加到列表中。但它只获得第一个和最后一个对象。怎么了。

import java.util.*;
class List{
Customer ptr;
public void add(Customer customer){
Customer temp = customer;
if(ptr==null){
ptr = temp;
}else{
ptr.next = temp;
}
}
public int size(){
int size = 0;
Customer temp = ptr;
while(temp!=null){
size++;
temp = temp.next;
}
return size;
}
public void printList(){
Customer temp = ptr;
while(temp!=null){
System.out.println(temp);
temp = temp.next;
}
}

}
class Demo{
public static void main(String args[]){
List list = new List();
Customer c1 = new Customer("1001","Danapala");
Customer c2 = new Customer("1002","Gunapala");
Customer c3 = new Customer("1003","Somapala");
Customer c4 = new Customer("1004","Amarapala");
list.add(c1);
list.add(c2);
list.add(c3);
list.printList();
System.out.println(list.size());
}
}
class Customer{
String id;
String name;
Customer next;
public Customer(String id, String name){
this.id = id;
this.name = name;
}
public String toString(){
return id+" : "+name;
}
public boolean equals(Object ob){
Customer c=(Customer)ob;
return this.id.equals(c.id);
}
}`

最佳答案

您不断覆盖第二项。变化:

public void add(Customer customer){
Customer temp = customer;
if(ptr==null){
ptr = temp;
}else{
ptr.next = temp;
}
}

到:

public void add(Customer customer){
Customer temp = customer;
if(ptr==null){
ptr = temp;
}else{
Customer runner = ptr;
// go over the items of the list until you reach the
// last item (its "next" field is set to null)
while(runner.next != null){
runner= runner.next;
}
// now set the customer as the last item
runner.next= temp;
}
}

关于java - java中的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18153121/

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