数据结构与算法回顾之栈和队列
2010-12-11 20:00 yearN 阅读(808) 评论(0) 收藏 举报1. 栈是一种数据项按序排列的数据结构,只能在一端(称为栈顶(top))对数据项进行插入和删除。栈具有“后进先出”特点。
栈实现代码:
namespace System2.Collections.Generic
{
/// <summary>
/// 堆栈类
/// </summary>
/// <typeparam name="T">.net支持类型</typeparam>
public class Stack<T>
{
private List<T> pool = new List<T>();
public Stack() { }
public Stack(int n)
{
pool = new List<T>(n);
}
public void Clear()
{
pool.Clear();
}
public bool IsEmpty()
{
return pool.Count == 0;
}
public T Peek()
{
if (IsEmpty())
{
throw new Exception("堆栈为空!");
}
return pool[pool.Count - 1];
}
public T Pop()
{
if (IsEmpty())
{
throw new Exception("堆栈为空!");
}
T tmp = pool[pool.Count - 1];
pool.RemoveAt(pool.Count - 1);
return tmp;
}
public void Push(T element)
{
pool.Add(element);
}
public string ToString()
{
return pool.ToString();
}
}
}
2. 队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作。进行插入操作的端称为队尾,进行删除操作的端称为队头。队列中没有元素时,称为空队列。队列具有“先进先出”的特点。
队列实现代码:
namespace System2.Collections.Generic
{
/// <summary>
/// 队列类
/// </summary>
/// <typeparam name="T">.net支持类型</typeparam>
public class Queue<T>
{
private int first, last, size;
private T[] storage;
public Queue():this(100)
{
}
public Queue(int n)
{
size = n;
storage = new T[size];
first = last = -1;
}
public bool IsFull()
{
return first == 0 && last == size - 1 || first == last + 1;
}
public bool IsEmpty()
{
return first == -1;
}
public void Enqueue(T element)
{
if (last == size - 1 || last == -1)
{
storage[0] = element;
last = 0;
if (first == -1)
{
first = 0;
}
}
else
{
storage[++last] = element;
}
}
public T Dequeue()
{
T tmp = storage[first];
if (first == last)
{
last = first = -1;
}
else if (first == size - 1)
{
first = 0;
}
else
{
first++;
}
return tmp;
}
}
}
浙公网安备 33010602011771号