C# 数据结构-栈(自练习)

本文介绍了一种使用C#实现栈的基本运算的方法,包括构造空栈、判栈空、判栈满、进栈、退栈及取栈顶元素等操作,并通过具体代码示例详细解释了每种运算的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

栈的基本运算有六种:

构造空栈:InitStack(S)、

判栈空: StackEmpty(S)、

判栈满: StackFull(S)、

进栈: Push(S,x)、可形象地理解为压入,这时栈中会多一个元素

退栈: Pop(S) 、可形象地理解为弹出,弹出后栈中就无此元素了。

取栈顶元素:StackTop(S),不同与弹出,只是使用栈顶元素的值,该元素仍在栈顶不会改变。

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace Stack

{

    class Stack

    {       

        private int count;

        private int current;

        private int[] items;

 

        public Stack(int capacity)

        {           

            items = new int[capacity];

            this.count = 0;

            this.current = 0;

        }

 

        public void Push(int item)

        {

            try

            {

                items[count]=item;

                current = item;

                count++;

            }

            catch(IndexOutOfRangeException)

            {

                throw new IndexOutOfRangeException("Stack is out of top. Can't push any more");

            }

        }

 

        public int Pop()

        {

            try

            {               

                int current = items[count-1];

                items[count-1] = 0;

                count--;

                if (count == 0)

                    this.current = 0;

                else if (count > 0)

                    this.current = items[count - 1];

                return current;

            }

            catch (IndexOutOfRangeException)

            {

                throw new IndexOutOfRangeException("Stack is at bottom.Can't pop any more.");

            }

        }

        /// <summary>

        /// Return true if Stack is empty.

        /// </summary>

        /// <returns></returns>

        public bool IsEmpty()

        {

            return count == 0 ? true : false;            

        }

        /// <summary>

        /// Return true if Stack is full.

        /// </summary>

        /// <returns></returns>

        public bool IsFull()

        {

            return count == items.Length ? true : false;

        }

 

        public int Current

        {

            get { return current; }

        }       

    }

}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值