我将这个列表作为一个环做了。我可以在这里获得第2,第3个元素的前一个对象。但是如果我要获得前一个元素,它将返回null。任何人都可以更正此代码。
class Ring {
Customer ptr;
void add(Customer customer) {
Customer temp = customer;
if (ptr == null) {
ptr = temp;
} else {
Customer x = ptr;
Customer n = ptr;
while (x.next != null) {
x = x.next;
n.next.prev = n;
n = n.next;
}
x.next = temp;
}
}
void printList() {
Customer temp = ptr;
System.out.println(temp.next.next.next.prev);
while (temp != null) {
//System.out.println(temp);
temp = temp.next;
}
}
}
class Main {
public static void main(String args[]) {
Ring list = new Ring();
Customer c1 = new Customer("10011", "A");
Customer c2 = new Customer("10012", "B");
Customer c3 = new Customer("10013", "C");
Customer c4 = new Customer("10014", "D");
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
list.printList();
}
}
class Customer {
String id;
String name;
Customer next;
Customer prev;
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 :(得分:0)
在你的添加功能中,就在while循环之后
x.next = temp;
这很棒,但你也需要这样做
x.next = temp;
temp.prev = x;
到最后一个项目将指向它的上一个项目
因此,您添加到列表中的每个项目都位于列表的最后一个项目中,只有当下一个项目放入列表时才会指向它的上一个项目
void add(Customer customer)
{
Customer temp = customer;
if (ptr == null)
{
ptr = temp;
}
else
{
Customer x = ptr;
Customer n = ptr;
while (x.next != null)
{
x = x.next;
n.next.prev = n;
n = n.next;
}
x.next = temp;
temp.prev = x;
ptr.prev = temp;// ******** edited line ******
}
}
答案 1 :(得分:0)
在您的类add
中的方法Ring
中:如果您只是转到最后一个元素然后执行链接,那么您的else
子句会更简单:
void add(Customer customer) {
Customer temp = customer;
if (ptr == null) {
ptr = temp;
} else {
Customer x = ptr;
while (x.next != null) {
x = x.next;
}
x.next = customer;
customer.prev = x;
customer.next = ptr;
ptr.prev = customer;
}
}