接口是按照课本上的ADT定义编写的,其余部分自己编写,泛型编程,这样的话可以有更加广泛的用途。
程序可以编译用过。
///链表
class singleLinkedList<T>
{
public T data;
public singleLinkedList<T> next;
public singleLinkedList()
{
data = default(T);
next = null;
}
}
///栈与队列
///栈
interface iStack<T>
{
void InitStack();
void DestoryStack();
void ClearStack();
bool StackEmpty();
int StackLength();
void GetTop(ref T value);
void Push(T value);
void Pop(ref T value);
bool StackTraverse(visit<T> tra);
}
///顺序栈
class SqStack<T> : iStack<T>
{
static int initSize = 50;
static int stackInr = 50;
T[] data;
int curSize;
int top;
int limit;
public void InitStack()
{
curSize = 0;
limit = initSize;
data = new T[initSize];
}
public void DestoryStack()
{
data = null;
curSize = 0;
top = 0;
}
public void ClearStack()
{
curSize = 0;
top = 0;
}
public bool StackEmpty()
{
if (curSize == 0)
{
return true;
}
return false;
}
public int StackLength()
{
return curSize;
}
public void GetTop(ref T value)
{
value = data[top];
--top;
}
public void Push(T value)
{
if (top < limit - 5)
{
data[top + 1] = value;
++top;
curSize++;
}
else
{
limit += stackInr;
data[top + 1] = value;
++top;
curSize++;
}
}
public void Pop(ref T value)
{
if (top > 0)
{
value = data[top];
data[top] = default(T);
--top;
}
else
{
value = default(T);
}
}
public bool StackTraverse(visit<T> tra)
{
for (int i = 0; i < top; i++)
{
if (tra(data[i]))
{
return false;
}
}
return true;
}
}
///顺序栈
///链式栈
class LinkedStack<T> : iStack<T>
{
singleLinkedList<T> head;
int curSize;
singleLinkedList<T> top;
public void InitStack()
{
head = new singleLinkedList<T>();
top = head;
curSize = 0;
}
public void DestoryStack()
{
head = null;
}
public void ClearStack()
{
head = null;
}
public bool StackEmpty()
{
if (0 == curSize)
{
return true;
}
else
{
return false;
}
}
public int StackLength()
{
return curSize;
}
public void GetTop(ref T value)
{
singleLinkedList<T> p = head;
if (p.Equals(top))
{
value = top.data;
}
else
{
while (p.next != null)
{
if (p.next.Equals(top))
{
value = p.next.data;
}
else
{
p = p.next;
}
}
}
}
public void Push(T value)
{
singleLinkedList<T> tmp = new singleLinkedList<T>();
top.next = tmp;
curSize++;
}
public void Pop(ref T value)
{
singleLinkedList<T> p = head;
if (p.Equals(top))
{
value = top.data;
}
else
{
while (p.next != null)
{
if (p.next.Equals(top))
{
value = p.next.data;
--curSize;
top = p;
}
else
{
p = p.next;
}
}
}
}
public bool StackTraverse(visit<T> tra)
{
singleLinkedList<T> p = head;
while (p != null && p.next != null)
{
if (tra(p.data))
{
return false;
}
p = p.next;
}
return true;
}
}
///链式栈
///栈