学习用书是Robert Sedgewick的算法(第四版),书中代码是用JAVA写的,于是改用C#重写其中的相关代码。
栈Stack
isEmpty 判断栈是否为空
size 返回栈大小的int值
push 添加一个对象
pop 弹出一个对象
public class Stack<T>
{
public class Node
{
public T t;
public Node next;
}//链表
private int N;
public Node first;
public bool isEmpty()
{
return N == 0;
}//判断是否为空
public int size()
{
return N;
}//判断栈的大小
public void push(T t)
{
Node oldfirst = first;
first = new Node();
first.t = t;
first.next = oldfirst;
N++;
}//添加一个对象
public T pop()
{
T t = first.t;
first = first.next;
N--;
return t;
}//取出一个对象
public IEnumerator<T> GetEnumerator()
{
return IteratorMethod();
}
public IEnumerator<T> IteratorMethod()
{
Node current = first;
while (current != null)
{
yield return current.t;
current = current.next;
}
}//实现迭代
}
队列Queue
isEmpty 返回队列是否为空的bool值
size 返回队列大小的int值
enqueue 添加一个对象
dequeue 弹出一个对象
public class Queue<Q>
{
public Node first;
public Node last;
public int N;
public class Node
{
public Q q;
public Node next;
}
public bool isEmpty()
{
return N == 0;
}//判断是否为空
public int size()
{
return N;
}//判断队列的大小
public void enqueue(Q q)
{
Node oldlast = last;
last = new Node();
last.q = q;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
}
public Q dequeue()
{
Q q = first.q;
first = first.next;
if (isEmpty()) last = null;
N--;
return q;
}
public IEnumerator<Q> GetEnumerator()
{
return IteratorMethod();
}
public IEnumerator<Q> IteratorMethod()
{
Node current = first;
while (current != null)
{
yield return current.q;
current = current.next;
}
}//实现迭代
}