算法学习1——在C#中用链表实现可迭代的泛型栈和队列

学习用书是Robert Sedgewick的算法(第四版),书中代码是用JAVA写的,于是改用C#重写其中的相关代码。

栈Stack

isEmpty 判断栈是否为空

size 返回栈大小的int值

push 添加一个对象

pop 弹出一个对象

    public class Stack<T>
    {
        public class Node
        {
            public T t;
            public Node next;
        }//链表

        private int N;
        public Node first;

        public bool isEmpty()
        {
            return N == 0;
        }//判断是否为空

        public int size()
        {
            return N;
        }//判断栈的大小

        public void push(T t)
        {
            Node oldfirst = first;
            first = new Node();
            first.t = t;
            first.next = oldfirst;
            N++;
        }//添加一个对象

        public T pop()
        {
            T t = first.t;
            first = first.next;
            N--;
            return t;
        }//取出一个对象

        public IEnumerator<T> GetEnumerator()
        {
            return IteratorMethod();
        }

        public IEnumerator<T> IteratorMethod()
        {
            Node current = first;

            while (current != null)
            {
                yield return current.t;
                current = current.next;
            }
        }//实现迭代
}

队列Queue

isEmpty 返回队列是否为空的bool值

size 返回队列大小的int值

enqueue 添加一个对象

dequeue 弹出一个对象

        public class Queue<Q>
        {
            public Node first;
            public Node last;
            public int N;

            public class Node
            {
                public Q q;
                public Node next;
            }

            public bool isEmpty()
            {
                return N == 0;
            }//判断是否为空

            public int size()
            {
                return N;
            }//判断队列的大小

            public void enqueue(Q q)
            {
                Node oldlast = last;
                last = new Node();
                last.q = q;
                last.next = null;
                if (isEmpty()) first = last;
                else oldlast.next = last;
                N++;
            }

            public Q dequeue()
            {
                Q q = first.q;
                first = first.next;
                if (isEmpty()) last = null;
                N--;
                return q;
            }

            public IEnumerator<Q> GetEnumerator()
            {
                return IteratorMethod();
            }

            public IEnumerator<Q> IteratorMethod()
            {
                Node current = first;

                while (current != null)
                {
                    yield return current.q;
                    current = current.next;
                }
            }//实现迭代
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值