0
点赞
收藏
分享

微信扫一扫

C# 2种顺序栈(泛型和object)

南柯Taylor 2022-07-14 阅读 15


using System;
using System.Collections.Generic;

namespace ConsoleApp1
{

class Stack<Ttype>
{
private int top=0;
private int bottom=0;
private int maxSize;
private Ttype[] element;
public Stack(int size)
{
element = new Ttype[size+1];
maxSize = size;
}
public bool Push(Ttype x)
{
if(top-bottom== maxSize)
return false;
else
{
element[top++] = x;
return true;
}
}
public Ttype Pop()
{
Ttype x = default(Ttype);
if (top != bottom)
{
x = element[--top];
}
return x;
}
public Ttype Peep()
{
Ttype x = default(Ttype);
if (top != bottom)
{
int temp = top - 1;
x = element[temp];
}
return x;
}
}

class Stack_object
{
private int top = 0;
private int bottom = 0;
private int maxSize;
private object[] element; //可以不同类型
public Stack_object(int size)
{
element = new object[size + 1];
maxSize = size;
}
public bool Push(object x)
{
if (top - bottom == maxSize)
return false;
else
{
element[top++] = x;
return true;
}
}
public object Pop()
{
object x = default(object);
if (top != bottom)
{
x = element[--top];
}
return x;
}
public object Peep()
{
object x = default(object);
if (top != bottom)
{
int temp = top - 1;
x = element[temp];
}
return x;
}
}
class Program
{
static void Main(string[] args)
{
var A = new int[]{ 1, 2, 3 };
var B = new double []{ 1.1, 2.2, 3.3 };
Stack<int> s = new Stack<int>(3);
foreach (var item in A)
{
s.Push(item);
}
Console.WriteLine(s.Peep());


Stack_object s1 = new Stack_object(6);
foreach (var item in A)
{
s1.Push(item);
}
foreach (var item in B)
{
s1.Push(item);
}
for(int i = 0; i < 6; i++)
{
var x = s1.Pop();
Console.WriteLine(x);
}


}
}

}


举报

相关推荐

C# 泛型

C# 泛型介绍

c#泛型(generic)

C# 泛型分析

0 条评论