想要获取最后一个元素的上一个对象。但是返回null

时间:2013-08-14 10:19:21

标签: java algorithm data-structures

我将这个列表作为一个环做了。我可以在这里获得第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);
}
}  

2 个答案:

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

}