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