我有一個將在控制臺應用程式中使用的通用堆疊。我需要堆疊的行為類似于 .Net 堆疊,但具有額外的功能。下面是堆疊的部分代碼
class DynamicGenericStack<T>
{
private class Node
{
public T element { get; private set; }
public Node Next { get; set; }
public Node(T element, Node prevNode)
{
this.element = element;
Next = null;
Previous = null;
if (prevNode != null) //if this is not the first node
prevNode.Next = this;
}
}
private Node head, tail;
public int Count { get; private set; } //Count
public DynamicStack()
{
this.head = null;
this.tail = null;
this.Count = 0;
}
public void Push(T item)
{
if (this.head == null)
this.head = this.tail = new Node(item, null);
else
tail = new Node(item, tail);
Count ;
} Push
public T Peek()
{
return tail.element;
} Peek
public T Pop()
{
if (Count > 0)
{
T item = tail.element;
Node prev = null, current = head;
while (current != tail)
{
prev = current;
current = current.Next;
}
tail = prev;
Count--;
return item;
}
return default(T);
}
}
如何實作上面的 pop 方法來刪??除尾節點,而不必像在上面的代碼中使用while回圈那樣遍歷整個串列?有什么方法可以跟蹤尾節點并直接將其洗掉?
uj5u.com熱心網友回復:
單個鏈表對于堆疊來說已經足夠了,只需要一個頭參考。
壓入堆疊:
create new_node
new_node.next = head;
head = new_node;
count ;
從堆疊中彈出:
if(count == 0)
return null;
tmp_node = head;
head = head.next;
count--;
return tmp_node.element;
uj5u.com熱心網友回復:
在堆疊中,您對底部并不真正感興趣。您有三種主要方法:
- push:在頂部添加一個新專案
- pop:移除頂部
- 頂部:讀取頂部
更改 1:下一個 -> 上一個
您將需要始終跟蹤頂部是什么,因此您需要知道之前的元素是什么。
public Node Prev { get; set; }
變化 2:對 Node 建構式應用相同的想法
public Node(T element, Node prevNode)
{
this.element = element;
Next = null;
Previous = null;
if (prevNode != null) //if this is not the first node
prevNode.Prev = this;
}
變化 3:在 Pop 應用此邏輯
public T Pop()
{
T element = default(T);
if (Count > 0)
{
element = tail.element;
if (tail.Prev != null) {
tail = tail.Prev;
} else {
head = tail = null;
}
}
return element;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460191.html
上一篇:無法為我的通用方法使用介面
