在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);
}
}
答案 0 :(得分:2)
while (size != index) {
size--;
temp = temp.next;
System.out.println(size + "------" + index);
}
return temp;
似乎是罪魁祸首。你的循环计数器从size()递减到所需的索引 而你的参考正在向前推进列表。 这意味着大小的值与您正在查看的索引没有真正的相似之处。
我用
int i =0;
while(++i <= index && i < size){
temp = temp.next;
}
if (i == index) {
return temp
} else {
//off the end, so throw exception
}
答案 1 :(得分:1)
由于这是一项任务,因此为您提供解决方案是不恰当的(或为了您的长远利益)...
基本问题是,您的get(i)
方法未将值返回到位置i
。
这应该足以让你弄清楚它到底在做什么......从而修复它。
答案 2 :(得分:0)
看起来你正以非常复杂的方式做一些非常简单的事情。
我建议:
首先,从客户中删除“下一个”字段。
然后,不要费心编写自己的List类。 Java有几个非常好的List实现。
示例:
import java.util。*; class DemoList {
public static void main(String args[]) {
List<Customer> list = new ArrayList<Customer>();
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);
//first customer:
System.out.println(list.get(0)); //zero-based
//all customers:
for (Customer c : list) {
System.out.println(c);
}
}
}