0

In this code, I want to remove the last object from list using removeLast. But it removes 1st element. How can I remove last element using removeLast method. https://stackoverflow.com/editing-help

List.java:

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 void removeLast() {
        Customer temp = listPtr;
        if (listPtr != null) {
            listPtr = temp.next;
        }
    }

    public void removeAll() {
        Customer temp = listPtr;
        while (temp != null) {
            listPtr = temp.next;
            temp = temp.next;
        }
    }

    public int size() {
        int size = 0;
        Customer temp = listPtr;
        while (temp != null) {
            size++;
            temp = temp.next;
        }
        return size;
    }

    public void printList() {
        Customer temp = listPtr;
        while (temp != null) {
            System.out.println(temp);
            temp = temp.next;
        }
    }
}

DemoList.java:

class DemoList {

    public static void main(String args[]) {
        List list = new List();
        Customer c1 = new Customer("10011", "Jason");
        Customer c2 = new Customer("10012", "George");
        Customer c3 = new Customer("10013", "Sam");
        list.add(c1);
        list.add(c2);
        list.add(c3);
        list.removeLast();

        list.printList();

    }
}

Customer.java:

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

2 回答 2

1

您还需要跟踪倒数第二个元素

public void removeLast() {
    if (listPtr != null) {
      Customer x1 = listPtr;
      Customer x2 = listPtr;
      while (x2.next != null) {
        x1 = x2;
        x2 = x2.next;
      }
      x1.next = null; // delete last
      index--;
    }
}

您当前的代码实际上只是将指针向上移动到列表中

    Customer temp = listPtr;
    if (listPtr != null) {
        listPtr = temp.next; // point to second element
    }
于 2013-08-11T14:55:03.297 回答
-2

问题是您需要获取不是最后一个,而是倒数第二个的元素。这样你就可以告诉那个元素它的“下一个”是空的。

以下代码可能会有所改进,但此解决方案对您有用。

public void removeLast() {
    Customer temp = listPtr;  
    while(temp.next.next!=null){
        temp = temp.next;
    } 
    temp.next=null;   
}
于 2013-08-11T15:00:35.320 回答