在这段代码中,我想使用removeLast从列表中删除最后一个对象。但它删除了第一个元素。如何使用removeLast方法删除最后一个元素。 https://stackoverflow.com/editing-help
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;
}
}
}
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();
}
}
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);
}
}
答案 0 :(得分: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
}
答案 1 :(得分:-2)
问题是你需要获得不是最后的元素,但是倒数第二个元素。通过这种方式,您可以告诉该元素它的“下一个”是空的。
以下代码可能会有所改进,但此解决方案适合您。
public void removeLast() {
Customer temp = listPtr;
while(temp.next.next!=null){
temp = temp.next;
}
temp.next=null;
}