[英]How do I delete the last occurrence in a circular linked list? (java)
I want to make a method that deletes the last occurrence of a value given in an argument in a circular linked list.我想创建一个方法来删除循环链表中参数中给定值的最后一次出现。
I tried to do it and this is my approach:我试图这样做,这是我的方法:
public void deleteLastOccurence(int value) {
Element cur = this.head;
Element prev = null;
Element tmp = null;
if(this.head == null)
return;
if(this.rear.data == value) {
this.head = this.rear = null;
return;
}
// while(cur != this.rear) {
while(cur.next != this.head && cur.next.data != value) {
prev = cur;
tmp = cur.next;
// cur = cur.next;
}
// cur = cur.next;
// }
prev.next = tmp.next;
}
But I don't think that I am deleting the last occurrence, because what if the value that I want to delete is right next to the same value.但我不认为我正在删除最后一次出现,因为如果我要删除的值就在同一个值旁边怎么办。
Separate finding the node from deleting the node.将查找节点与删除节点分开。 The method is simplified to
该方法简化为
public void deleteLastOccurrence(int value) {
Element lastOccurrence = findLastOccurrence(value);
if (null != lastOccurrence) {
deleteElement(lastOccurrence);
}
}
Assuming that a circular list means that the head.prev
is the rear
and the rear.next
is the head
.假设一个循环列表意味着
head.prev
是rear
,而后部rear.next
是head
。 To find the last occurrence, start at the rear
of the list and iterator towards the head
.要查找最后一次出现,从列表的
rear
开始,迭代器朝向head
。 The last occurrence is thus the first match you encounter.因此,最后一次出现是您遇到的第一个匹配项。
private Element findLastOccurrence(int value) {
if (isEmpty()) {
return null;
}
Element current = rear;
do {
if (current.value == value) {
return current;
}
current = current.prev;
} while (current != rear); // we're back at the rear with no match
return null;
}
The isEmpty()
and deleteElement(Element)
methods are left as an exercise for the reader. isEmpty()
和deleteElement(Element)
方法留给读者作为练习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.