*因为要写顺序栈和链栈所以写了个接口,也是第一次接触接,还不错。*
栈 先进后出 后进先出
接口的定义
namespace 栈
{
interface Interface1<T>
{
int Count { get; }
int GetLength();
void IsEmpty();
void Clear();
void Push(T item);
T Pop();
T Peek();
}
}
顺序栈类
namespace 栈
{
class SeqStack<T> : Interface1<T>
{
private int top;
private T[] date;
public SeqStack(int size)
{
this.date = new T[size];
this.top = -1;
}
public SeqStack(): this(10)
{
}
public int Count { get { return top + 1; } }
public void Clear()
{
top = -1;
}
public int GetLength()
{
return Count ;
}
public void IsEmpty()
{
if(top==-1)
{
Console.WriteLine("IsEmpty");
}
else
{
Console.WriteLine("IsFull");
}
}
public T Peek()
{
return date[top] ;
}
public T Pop()
{
T temp;
temp = date[top];
top--;
return temp;
}
public void Push(T item)
{
top++;
date[top] = item;
}
}
}
节点类
在这里插入代码片
namespace 栈
{
class Node<T>
{
private Node<T> next;
private T date;
public Node()
{
next = null;
date = default(T);
}
public Node(T item)
{
this.date = item;
this.next = null;
}
public Node(Node<T> next)
{
this.next = next;
this.date = default(T);
}
public Node(Node<T>next,T item)
{
this.next = next;
this.date = item;
}
public Node<T> Next
{
get { return next; }
set { next = value; }
}
public T Date
{
get { return date; }
set { date = value; }
}
}
}
链类
namespace 栈
{
class LinkStack<T> : Interface1<T>
{
private Node<T> top = new Node<T>();
private int count;
public LinkStack()
{
top = null;
count = 0;
}
public int Count
{
get { return count; }
}
public void Clear()
{
count = 0;
}
public int GetLength()
{
return count;
}
public void IsEmpty()
{
throw new NotImplementedException();
}
public T Peek()
{
return top.Date;
}
public T Pop()
{
Node<T> tempNode = new Node<T>();
tempNode = top.Next;
top = tempNode;
return top.Date;
}
public void Push(T item)
{
Node<T> tempNode = new Node<T>(item);
tempNode.Next = top;
top = tempNode;
count++;
}
}
}
主函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 栈
{
class Program
{
static void Main(string[] args)
{
LinkStack<string> stack = new LinkStack<string>();
stack.Push("741");
stack.Push("852");
stack.Push("963");
Console.WriteLine(stack.Count);
Console.WriteLine("栈顶元素为" + stack.Peek());
stack.Pop();
Console.WriteLine("栈顶元素为" + stack.Peek());
stack.Pop();
Console.WriteLine("栈顶元素为" + stack.Peek());
Console.WriteLine(stack.Count);
/* for(int i=0;i<stack.GetLength();i++)
{
Console.WriteLine();
}*/
Console.ReadKey();
}
}
}
298

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



