您的位置:首页 > 编程语言 > C#

C#简单实现顺序栈与链式栈

2018-02-26 21:01 253 查看
其实就是顺序表与链表的简化版本

接口:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace learn_03
{
interface IStackDS<T>
{
int Count { get; }
int GetLength();
bool IsEmpty();
void Clear();
void Push(T item);
T Pop();
T Peek();
}
}



顺序栈:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace learn_03
{
class SeqStack<T>:IStackDS<T>
{
private T[] data;
private int top;

public SeqStack(int size)
{
data = new T[size];
top = -1;
}
public SeqStack()
: this(10) { } //默认长度10

public int Count
{
get { return top + 1; }
}
public int GetLength()
{
return Count;
}

public bool IsEmpty()
{
return Count == 0;
}
public void Clear()
{
top = -1;
}

public void Push(T item)
{
data[top + 1] = item;
top++;
}
public T Pop()
{
T temp = data[top];
top--;
return temp;
}
public T Peek()
{
return data[top];
}
}
}

链栈:

节点类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace learn_03
{
class Node<T>
{
private T data;
private Node<T> next;

public Node()
{
data = default(T);
next = null;
}
public Node(T data)
{
this.data = data;
next = null;
}
public Node(T data, Node<T> next)
{
this.data = data;
this.next = next;
}
public Node(Node<T> next)
{
data = default(T);
this.next = next;
}
public T Data
{
get { return data; }
set { data = value; }
}
public Node<T> Next
{
get { return next; }
set { next = value; }
}
}
}

实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace learn_03
{
class LinkStack<T>:IStackDS<T>
{

private Node<T> top;
private int count = 0;

public int Count
{
get { return count; }
}
public int GetLength()
{
return count;
}

public bool IsEmpty()
{
return count == 0;
}
public void Clear()
{
count = 0;
top = null;
}

public void Push(T item)
{
Node<T> newNode = new Node<T>(item);
newNode.Next = top;
top = newNode;
count++;
}
public T Pop()
{
T data = top.Data;
top = top.Next;
return data;
count--;
}
public T Peek()
{
return top.Data;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: