Summary analysis of queue and stack of data structure

1. Preface:

Queues and stacks are also two common data structures in the data structure. Queues and stacks are also complementary in the actual use scenarios. Here is a brief summary, if there are any differences, point more, thank you.

2. Introduction to Queues

Queues, as its name implies, means queuing. According to our real life, queuing means queuing in order, first come first, in fact, queues in the program data structure have the same effect, and first come first.

Queues have some of the following characteristics:

(1) Flexible operation, no length is required at initialization, its length increases automatically (default length is 32)

Note: In practice, specifying a length at initialization can improve efficiency if the length can be predicted beforehand

2. Introduction of generics, queues can be defined with data types to avoid boxing and unboxing

3. Stored data meets FIFO principle

       

Several common methods of queuing in c#are:

    • The Count:Count property returns the number of elements in the queue.
    • The Enqueue:Enqueue() method adds an element to one end of the queue.
    • The Dequeue:Dequeue() method reads and deletes elements at the head of the queue.If there are no more elements in the queue when the Dequeue() method is called, an exception of type InvalidOperationException is thrown.
    • The Peek:Peek() method reads an element from the head of the queue without deleting it.
    • TrimExcess: The TrimExcess() method resets the capacity of the queue.The Dequeue() method deletes elements from the queue, but it does not reset the capacity of the queue.To remove empty elements from the head of the queue, use the TrimExcess() method.
    • The Clear:Clear() method removes all elements from the queue.
    • ToArray: ToArray() copies the queue to a new array.

The following simulates the implementation of a message queue by using a queue:

 

using System;
using System.Collections;
using System.Collections.Generic;

namespace dataStructureQueueTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("adopt Queue To simulate the implementation of a message queue");
            QueueTest queueTest = new QueueTest();

            while (true)
            {
                Console.WriteLine("Please enter the type of operation you operate on:1:Represents the generation of a message, 2: Represents consumption of a message");
                string type = Console.ReadLine();
                if (type == "1")
                {
                    Console.WriteLine("Please enter a specific message:");
                    string inforValue = Console.ReadLine();
                    queueTest.InformationProducer(inforValue);
                }
                else if (type == "2")
                {
                    //// In the consumer message, simulate the next consumption scenario, consumption success and consumption failure

                    object inforValue = queueTest.InformationConsumerGet();
                    if (inforValue == null)
                    {
                        Console.WriteLine("There is currently no message to consume");
                    }
                    else
                    {
                        Console.WriteLine("The message you get is:" + inforValue);

                        Console.WriteLine("Please enter message consumption results:1:Successful consumption of news, 2: Message consumption failure");
                        string consumerState = Console.ReadLine();

                        ///// Note: This operation is thread insecure and should not be used directly on multiple threads
                        if (consumerState == "1")
                        {
                            queueTest.InformationConsumerDel();
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Error in operation, please select again");
                }
            }
        }
    }

    /// <summary>
    /// Queue Practice
    /// </summary>
    public class QueueTest
    {
        /// <summary>
        /// Define a Queue
        /// </summary>
        public Queue<string> queue = new Queue<string>();

        /// <summary>
        /// Generate message--Queue
        /// </summary>
        /// <param name="inforValue"></param>
        public void InformationProducer(string inforValue)
        {
            queue.Enqueue(inforValue);
        }

        /// <summary>
        /// Consumer News---Out of Queue--Get data only, don't delete data
        /// </summary>
        /// <returns></returns>
        public object InformationConsumerGet()
        {
            if (queue.Count > 0)
            {
                return queue.Peek();
            }

            return null;
        }

        /// <summary>
        /// Consumer News---Out of Queue---Get data while deleting it
        /// </summary>
        /// <returns></returns>
        public string InformationConsumerDel()
        {
            if (queue.Count > 0)
            {
                return queue.Dequeue();
            }

            return null;
        }
    }
}

 

 

3. Introduction of Stack

Stacks and queues are similar in use, except that the data storage of the stack meets the FIFO principle, and the stack has the following characteristics:

1. Flexible operation, no length is required for initialization, and the length increases automatically (default length is 10)

Note: In practice, specifying a length at initialization can improve efficiency if the length can be predicted beforehand

2. Introduction of generics, stack can specify data type when defining to avoid boxing and unboxing

3. Stored data meets FIFO principle

Several common methods of stacking in c#are:

  • The Count:Count property returns the number of elements in the stack.
  • The Push:Push() method adds an element to the top of the stack.
  • The Pop:Pop() method deletes an element from the top of the stack and returns it.If the stack is empty, an exception of type InvalidOperationException is thrown.
  • The Peek:Peek() method returns the top element of the stack without deleting it.
  • The Contains:Contains() method determines if an element is on the stack and returns true if it is.

Following is a stack that simulates the implementation of the browser's fallback forward operation

 

using System;
using System.Collections.Generic;

namespace dataStructureStackTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //// Use stack to simulate browser fallback forward operation
            ////   1,Define two stacks to record the fallback address set and the forward address set, respectively
            ////   2,When operating a specific fallback or forward operation
            ////      If the same as the previous operation, then take out one data from the corresponding queue and store it in another queue
            Console.WriteLine("This exercise simulates a browser's backward-forward action:");

            /// Assume the browser has browsed 20 site records
            StackTest stackTestBack = new StackTest(20);
            StackTest stackTestGo = new StackTest(20);
            for (int i = 0; i < 20; i++)
            {
                stackTestBack.PushStack("website" + (i + 1).ToString());
            }

            //// Record last action
            string beforOpert = "";
            while (true)
            {
                Console.WriteLine("");
                Console.WriteLine("Please enter the type of operation you operate on:1:Back, 2: Forward");
                string type = Console.ReadLine();

                if (type == "1")
                {
                    //// Stack Out
                    if (beforOpert == type)
                    {
                        stackTestGo.PushStack(stackTestBack.GetAndDelStack());
                    }
                    string wbeSit = stackTestBack.GetStack();
                    Console.WriteLine("Back to page:" + wbeSit);
                    beforOpert = type;
                }
                else if (type == "2")
                {
                    //// Stack Out
                    if (beforOpert == type)
                    {
                        stackTestBack.PushStack(stackTestGo.GetAndDelStack());
                    }
                    string wbeSit = stackTestGo.GetStack();

                    Console.WriteLine("Back to page:" + wbeSit);
                    beforOpert = type;
                }
                else
                {
                    Console.WriteLine("Please enter the correct operation!!");
                }
            }
        }
    }

    /// <summary>
    /// Queue Practice
    /// </summary>
    public class StackTest
    {
        /// <summary>
        /// Define a stack
        /// </summary>
        public Stack<string> stack;

        /// <summary>
        ///No parameter constructor, stack initialized to default length
        /// </summary>
        public StackTest()
        {
            stack = new Stack<string>();
        }

        /// <summary>
        ///Parameter constructor, stack initialized to specified length
        ///If, when defining a queue, you know the length of data you need to store, it is best to estimate the length and initialize the specified length
        /// </summary>
        public StackTest(int stackLen)
        {
            stack = stackLen > 0 ? new Stack<string>(stackLen) : new Stack<string>();
        }

        /// <summary>
        /// Push
        /// </summary>
        /// <param name="inforValue"></param>
        public void PushStack(string inforValue)
        {
            stack.Push(inforValue);
        }

        /// <summary>
        /// Stack out (but don't delete)
        /// </summary>
        /// <returns></returns>
        public string GetStack()
        {
            if (stack.Count > 0)
            {
                return stack.Peek();
            }

            return null;
        }

        /// <summary>
        /// Stack out (and delete)
        /// </summary>
        /// <returns></returns>
        public string GetAndDelStack()
        {
            if (stack.Count > 0)
            {
                return stack.Pop();
            }

            return null;
        }
    }
}

 

4. Summary of usage scenarios

Based on the characteristics of queues and stacks, here is a brief summary of some of the actual scenarios for using queues and stacks

Queue:

1. Asynchronous logging, where the use of the singleton mode is involved

2. Message Queuing

3. Business queuing, such as 12306 ticket purchase queuing

4. Other FIFO-compliant business operations

Stack:

1. Returnable action records, such as browser's rewind action

2. Computation expression matching, e.g. calculator expression calculation

3. Other business operations conforming to the FIFO principle

 

Enclosure:

For code for these exercises, upload it to github and take a look if you're interested:

https://github.com/xuyuanhong0902/dataStructureTest.git

Keywords: C# github calculator git

Added by minou on Sat, 16 Nov 2019 19:57:53 +0200