1

我制作了这份清单作为戒指工作。我可以在这里获得第二、第三元素的先前对象。但是如果我要获取最后一个元素的前一个,它会返回 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);
}
}  
4

2 回答 2

0

在你的 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 ******
    }

}
于 2013-08-14T10:26:46.530 回答
0

在您add的类中的方法中Ringelse如果您只转到最后一个元素然后执行链接,您的子句会更简单,如下所示:

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

}
于 2013-08-14T10:31:06.510 回答