interface IStack<T>
{
int GetLength(); //获取长度
bool IsEmpty();//是否为空
void Clear();//清空
void Push(T item);//添加
T Pop();//删除头数据
T GetTop();//取出头数据
}
public class Node<T>
{
private T data;
private Node<T> next;
public T Data
{
get { return data; }
set { data = value; }
}
public Node<T> Next
{
get { return next; }
set { next = value; }
}
public Node(T val,Node<T>p )
{
data = val;
next = p;
}
public Node(T val)
{
data = val;
// next = null ;
}
public Node( Node<T> p)
{
// data = default(T);
next = p;
}
public Node()
{
data = default (T );
next = null;
}
}
//线栈
public class SeqStack<T> : IStack<T>
{
private int matsize;
private T[] data;
private int top;
public int Matsize { get => matsize; }
public T[] Data { get => data; set => data = value; }
public int Top { get => top; }
public SeqStack(int size)
{
matsize = size;
data = new T[matsize];
top = -1;
}
public T this[int i]
{
get
{
if (i <= top && i > -1)
{
return data[i];
}
else
{
Console.WriteLine("数据不存在");
return default(T);
}
}
}
public bool IsFull()
{
return top==matsize-1;
}
public void Clear()
{
top = -1;
Array.Clear(data, 0, matsize);
}
public int GetLength()
{
return top + 1;
}
public T GetTop()
{
if (IsEmpty())
{
Console.WriteLine("Stack is empty!");
return default(T);
}
return data[top];
}
public bool IsEmpty()
{
return top == -1;
}
public T Pop()
{
T temp = default(T);
if (IsEmpty ())
{
Console.WriteLine("Stack is full!");
return temp ;
}
temp = data[top];
--top;
return temp;
}
public void Push(T item)
{
if (IsFull ())
{
Console.WriteLine("Stack is full!");return;
}
data[++top]=item;
}
}
//链栈
public class LinkStack<T> : IStack<T>
{
private Node<T> top;
private int num;
public int Num { get => num; }
internal Node<T> Top { get => top; set => top = value; }
public LinkStack()
{
top = null;
num = 0;
}
public T this[int i]
{
get
{
if (i < 0 || i > num)
return default(T);
Node<T> p = top;
for (int j = 0; j <num -i; ++j)
{
p = p.Next;
}
return p.Data;
}
}
public void Clear()
{
top = null;
num = 0;
}
public int GetLength()
{
return num;
}
public T GetTop()
{
if (IsEmpty())
{
Console.WriteLine("LinkStack is empty!");
return default(T);
}
return top.Data;
}
public bool IsEmpty()
{
return num == 0 && top == null ? true:false ;
}
public T Pop()
{
if (IsEmpty ())
{
Console.WriteLine("LinkStack is empty!");
return default(T);
}
Node<T> p = top;
top = top.Next;
--num;
return p.Data;
}
public void Push(T item)
{
Node<T> q = new Node<T>(item);
if (top ==null)
{
top = q;
}
else
{
q .Next=top;
top = q;
}
++num;
}
}

被折叠的 条评论
为什么被折叠?



