数组共享双栈的实现

来源:互联网 发布:手机淘宝怎样使用花呗 编辑:程序博客网 时间:2024/06/10 09:01

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{ //数组共享双栈
public class ShareDoubleStack{
public int top1{get;set;}//第一个栈,栈底,即是数组的起始
public int top2{get;set;}//第二个栈,栈底,即是数组的结束
public int maxsize { get; set; }//定义该共享栈的 大小
public string[] data { get; set; }//定义一个数组 来存放栈内的节点内容
///
/// 构造函数 初始化
///
/// 栈的数组的大小 【int】
public ShareDoubleStack(int maxsize) {
this.top1 = -1;
this.top2 = maxsize;
this.maxsize = maxsize;
this.data = new string[maxsize];
}
///
/// 根据指定的参数,入栈
///
/// 入栈的参数【string】
/// 指定入的栈的参数,1代表数组底的一栈,2代表数组顶的2栈
public void Push(string data , int satckNumber ) {
if (this.top1+1==this.top2)
{
return;
}
if (satckNumber==1)
{
this.data[++this.top1] = data;
}
else if (satckNumber==2)
{
// Console.WriteLine(“2栈添加”);
this.data[–this.top2] = data;

         }     }     /// <summary>     /// 返回一个出栈的值     /// </summary>     /// <param name="satckNumber">指定出的栈的参数,1代表数组底的一栈,2代表数组顶的2栈<</param>     /// <returns></returns>     public string Pop(int satckNumber) {         string d;         if (satckNumber==1)         {             if (this.top1==-1)                 return null;             return d= this.data[this.top1--];         }        else if(satckNumber==2)         {               if (this.top2==this.maxsize)                 return null;             return d = this.data[this.top2++];         }else{         return null;         }     }      /// <summary>     ///  根据指定的参数,显示所有的栈数据      /// </summary>     /// <param name="stackNumber">指定显示的栈的参数,1代表数组底的一栈,2代表数组顶的2栈</param>     public void Show(int stackNumber) {         if (stackNumber==1)         {             if (this.top1 == -1)             {                 Console.WriteLine("1栈为空");                 return;             }             for (int i = this.top1; i >-1; i--)             {                 Console.WriteLine(data[i]);             }         }         else if (stackNumber==2)         {             if (this.top2==this.maxsize)             {                 Console.WriteLine("2栈为空");                 return;             }             for (int j = this.top2; j < this.maxsize; j++)             {                  Console.WriteLine(data[j]);             }         }     } }    //测试    class Program    {        static void Main(string[] args)        {            ShareDoubleStack sds = new ShareDoubleStack(6);            sds.Push("a",1);            sds.Push("b", 1);            sds.Push("c", 1);            sds.Push("aa",2);            sds.Push("bb",2);            sds.Push("cc",2);            sds.Show(1);            sds.Show(2);            Console.ReadKey();        }    }}
0 0
原创粉丝点击