您当前的位置: 首页 >  c#

光怪陆离的节日

暂无认证

  • 2浏览

    0关注

    1003博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C#实现堆栈结构的定义、入栈、出栈

光怪陆离的节日 发布时间:2022-06-27 16:44:51 ,浏览量:2

本文介绍C#实现堆栈结构的定义、入栈、出栈 1、栈的定义 /// /// 栈定义 /// public struct SqStack { public int[] data; public int top;//栈顶

    }

2、判断栈是否为空 /// /// 判断栈是否为空 /// /// /// bool StackEmpty(SqStack S) { if (S.top == -1) { return true; } else { return false; } } 3、栈初始化 /// /// 栈初始化 /// /// static void InitStack(ref SqStack S) { S.top = -1; }

4、压栈 /// /// 压栈 /// /// /// static bool Push(ref SqStack S,int e) { if (S.top >= MaxSize - 1) { return false; } S.top = S.top+1; S.data[S.top] = e;//先加1,再进栈 return true; } 5、出栈 /// /// 出栈 /// /// /// /// static bool PoP(ref SqStack S, ref int e) { if (S.top==-1) { return false; } e = S.data[S.top–];//出栈 return true; } 6、读取栈顶元素 /// /// ///读取栈顶元素 /// /// /// /// bool GetTop(ref SqStack S, ref int e) {

        if (S.top == -1) { return false; }
        e = S.data[S.top];//读取元素
        return true;

    }

7、实际main函数测试 public const int MaxSize = 50;//定义栈的元素最大值 static void Main(string[] args) { SqStack S = new SqStack() ; S.data = new int[MaxSize]; int x=0; //初始化栈 InitStack(ref S); //进栈 while (x!=999) { Console.WriteLine(“请输入栈元素”); x = int.Parse(Console.ReadLine());//字符转为整型 if (x != 999) { Push(ref S, x); }

        }
        Console.WriteLine("栈顶元素:"+S.data[S.top]+"栈的元素个数:"+(S.top+1));
        Console.WriteLine("出栈元素如下");
        while (S.top!=-1) {
            PoP(ref S,ref x);
            Console.WriteLine(x);
        }
        Console.ReadLine();

    }
关注
打赏
1665731445
查看更多评论
立即登录/注册

微信扫码登录

0.0393s