gpt4 book ai didi

java - 想要从第一个到最后一个元素。但最后回到第一

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:46:59 25 4
gpt4 key购买 nike

在 get 方法中,我想获取从第一个元素到最后一个元素的元素。但它以相反的顺序返回列表(从最后到第一个元素)。我怎样才能用这段代码解决这个问题?

import java.util.*;

class List {

Customer listPtr;
int index;

public void add(Customer customer) {
Customer temp = customer;
if (listPtr == null) {
listPtr = temp;
index++;
} else {
Customer x = listPtr;
while (x.next != null) {
x = x.next;
}
x.next = temp;
index++;
}
}

public Customer get(int index) {
Customer temp = listPtr;
int size = size();
if (index == 0) {
return listPtr;
} else {
while (size != index) {
size--;
temp = temp.next;
System.out.println(size + "------" + index);
}
return temp;
}
}

public int size() {
int size = 0;
Customer temp = listPtr;
while (temp != null) {
temp = temp.next;
size++;
}
return size;
}

public void printList() {
Customer temp = listPtr;
while (temp != null) {
System.out.println(temp);
temp = temp.next;
}
}
}

class DemoList {

public static void main(String args[]) {
List list = new List();
Customer c1 = new Customer("10011", "A");
Customer c2 = new Customer("10012", "B");
Customer c3 = new Customer("10013", "C");
Customer c4 = new Customer("10014", "D");
Customer c5 = new Customer("10015", "E");
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
System.out.println(list.get(1));
//list.printList();

}
}

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);
}
}

最佳答案

这个问题有点模棱两可。您似乎在问为什么 .get() 没有返回预期的元素?

while (size != index) {
size--;
temp = temp.next;
System.out.println(size + "------" + index);
}
return temp;

似乎是罪魁祸首。您的循环计数器正在从 size() 递减到所需的索引当您的引用资料在列表中向前移动时。这意味着 size 的值与您正在查看的索引没有任何相似之处。

我会用

int i =0;
while(++i <= index && i < size){
temp = temp.next;
}
if (i == index) {
return temp
} else {
//off the end, so throw exception
}

关于java - 想要从第一个到最后一个元素。但最后回到第一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18183635/

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