我制作这份 list 是为了作为一个戒指工作。我可以在这里获得第二个、第三个元素的先前对象。但是如果我要获取最后一个元素的前一个元素,它会返回 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);
}
}
最佳答案
在你的 add 函数中,就在 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 ******
}
}
关于java - 想要获取最后一个元素的前一个对象。但返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18229075/