栈的定义
栈(Stack)是只允许在一端进行插入或删除操作的线性表。
栈的示意图:
- 栈顶Top:线性表允许插入和删除的那一端。
- 栈底Bottom:固定的,不允许进行插入和删除的另一端。
数组实现
public class ArrayStack<T>
{
public T[] array;
public int top;
public int count;
public int capacity => array == null ? 0 : array.Length;
public ArrayStack(int capacity = 5)
{
array = new T[capacity];
top = 0;
count = 0;
}
public void Push(T value)
{
if (count >= capacity)
Extend();
array[top] = value;
top++;
count++;
}
public T Pop()
{
if (count == 0)
throw new Exception("Stack is empty");
top--;
T value = array[top];
count--;
return value;
}
public T Peek()
{
if (count == 0)
throw new Exception("Stack is empty");
return array[top - 1];
}
public void Extend()
{
int newCapacity = capacity * 2;
T[] newArray = new T[newCapacity];
for (int i = 0; i < top; i++)
newArray[i] = array[i];
array = newArray;
}
}
注意:取栈顶元素时取地是top-1的值,不是top的值;
链表实现
public class Node<T>
{
public T value { get; set; }
public Node<T> next { get; set; }
public Node() { }
public Node(T value)
{
this.value = value;
}
}
public class LinkListStack<T>
{
public Node<T> top;
public Node<T> bottom;
public int count;
public LinkListStack()
{
count = 0;
}
public void Push(T value)
{
Node<T> node = new Node<T>(value);
node.next = top;
top = node;
count++;
}
public T Pop()
{
if (count == 0)
throw new Exception("Stack is empty");
T value = top.value;
top = top.next;
count--;
return value;
}
public T Peek()
{
if (count == 0)
throw new Exception("Stack is empty");
return top.value;
}
}