9,数组实现泛型栈

2021-02-16 03:18

阅读:692

标签:调用   深度   maxsize   ++   数组   color   代码   深度优先搜索   div   

栈的用途比较广 

如:子进程调用,递归调用,表达式转换,二叉树遍历,深度优先搜索 等等

实现思路:

1)top=-1时栈为空,top=maxsize-1栈满

C#代码实现:

 1 using System;
 2 
 3 namespace 数据结构
 4 {
 5     public class ArrayStack 6     {
 7         //栈最大值
 8         private int MaxSize { get; set; }
 9         private T[] Item { get; set; }
10         //指向栈顶,当栈为空是初始化为-1
11         private int Top { get; set; } = -1;
12         //栈是否为空
13         public bool IsEmpt { get => Top == -1; }
14         //栈是否满了
15         public bool IsFull { get => Top == MaxSize - 1; }
16         public ArrayStack(int maxSize)
17         {
18             this.MaxSize = maxSize;
19             this.Item = new T[maxSize];
20         }
21         
22         //入栈
23         public void Push(T item)
24         {
25             if (IsFull)
26             {
27                 Console.WriteLine("栈满了哦");
28                 return;
29             }
30             Top++;
31             Item[Top] = item;
32         }
33 
34         //出栈
35         public T Pop()
36         {
37             if (IsEmpt)
38             {
39                 Console.WriteLine("栈空了哦");
40                 return default;
41             }
42             var item = Item[Top];
43             Top--;
44             return item;
45         }
46 
47         //偷看栈顶
48         public T Peek()
49         {
50             if (IsEmpt)
51             {
52                 Console.WriteLine("栈空了哦");
53                 return default;
54             }
55             return Item[Top];
56         }
57     }
58     public class ArrayStackDemo
59     {
60         public static void Main(string[] args)
61         {
62             var stack = new ArrayStackstring>(10);
63             Console.WriteLine("张三,李四,王五 入栈了");
64             stack.Push("张三");
65             stack.Push("李四");
66             stack.Push("王五");
67 
68             Console.WriteLine("王五,李四,张三 出栈了");
69             Console.WriteLine($"看谁在栈顶?{stack.Peek()}");
70             stack.Pop();
71             Console.WriteLine($"看谁在栈顶?{stack.Peek()}");
72             stack.Pop();
73             Console.WriteLine($"看谁在栈顶?{stack.Peek()}");
74             stack.Pop();
75             stack.Pop();
76         }
77     }
78 }

 

9,数组实现泛型栈

标签:调用   深度   maxsize   ++   数组   color   代码   深度优先搜索   div   

原文地址:https://www.cnblogs.com/xiaojvhuang/p/12709983.html


评论


亲,登录后才可以留言!