[英]Stack operations using Linked LIst in Java
我需要編寫一個使用鏈表實現堆棧的 class。 不同之處在於它應該從列表的尾部而不是頭部執行推送和彈出操作,而不需要維護對列表尾部節點的引用。
如何在不保留對尾節點的引用的情況下實現這一點?
你可以這樣做,但效率很低,因為每次你想做某事時,你都必須通過整個列表 go 。 當所有操作都在尾部執行時,您確實沒有任何理由要保留對頭部的引用。
但無論如何我都會這樣做:
class Entry<E> {
E object;
Entry<E> next;
public Entry(E obj) {
object = obj;
}
}
class StackList<E> {
Entry<E> head;
public void push(E element) {
if (head == null) {
// first
head = new Entry<E>(element);
return;
}
Entry<E> node = head;
while (node != null && node.next != null) {
node = node.next;
}
// node is now the tail
Entry<E> newEntry = new Entry<E>(element);
node.next = newEntry;
}
public E pop() {
if (head == null) {
// empty
return null;
}
Entry<E> node = head, previousNode = null;
while (node.next != null) {
previousNode = node;
node = node.next;
}
// node is now the tail
// previousNode is the next-to-last
if (previousNode != null) {
previousNode.next = null;
} else {
// there was only one thing
head = null;
}
return node.object;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.