Data Structures and Algorithms: Stack

A stack

Stack (Stack) is a combination of a set of the same data type, all operations were carried out at the top of the stack, with the "last out" (First In Last Out, FILO) characteristics. Application stack structure in the computer quite extensive, are often used to solve computer problems, such as recursive calls, subroutine calls and so on. Data structure stack principle, similar to the following:

1. Introduction Stack

Speaking after the last out (First In Last Out) concept, in fact, just as the buffet dinner plates stacked one by one by the desktop Internet, and when access to acquire from the top, this is the typical application stack concept. Since the stack is an abstract data structure (Abstract Data Type), which has a lower characteristic:

  1. Can only access data from the top of the stack.
  2. Data access in line with the principle of "last out" of.

Stack operations can refer to the following diagram:

The basic operation of the stack shown in the following table:

create Create an empty stack
push Pressure of the top of the data stack, and returns the new stack
pop Pop-up data from the top of the stack, and returns the new stack
isEmpty Determine whether the stack is empty stack, it returns true, not false returns
full Determine whether the stack is full, it returns true, not false returns

Stack programming art, comprising two ways design and structure of the array list structure, the following were introduced.

Second, the use arrays to implement a stack

An array structure to achieve the benefits of the stack is to design algorithms are quite simple, but if the size of the stack itself is changing, and the size of the array can only be defined first, then the array is too big and a waste of space planning, planning is too small it is not enough. See the following an example: using an array structure to design a C # program, using a loop control preparation pressed or pop elements, imitate the operand stack, which must include pressed (push) and the pop-up (pop) method, finally, the output of all the elements within the stack. code show as below:

Stack class definitions:

the using the System; 

namespace StackByArray 
{ 
    public  class StackArray 
    { 
        // used to simulate the stack array declaration 
        Private  int [] Stack;
         // define the top of the stack pointer points to 
        Private  int Top; 

        // Constructors 
        public StackArray ( int the stackSize) 
        { 
            // create arrays 
            stack = new new  int [the stackSize];
             // array index starts from 0, when the array is empty, the top of the stack pointer is -1 
            top = - . 1 ; 
        } 

        ///  <Summary> 
        ///The stack is pressed into the designated top of the stack data
         ///  </ Summary> 
        ///  <param name = "Data"> </ param> 
        ///  <Returns> </ Returns> 
        public  BOOL the Push ( int Data) 
        { 
            // determines whether the index is greater than the top of the stack array size 
            iF (top> = Stack.Length) 
            { 
                Console.WriteLine ( " the stack is full, can not join " );
                 return  to false ; 
            } 
            the else 
            { 
                // the data onto the stack, moved simultaneously on a Top 
                Stack [Top ++] = Data;
                 return  to true ;
            } 
        } 

        ///  <Summary> 
        /// determines whether the stack is empty stack, if it returns true, otherwise returns to false
         ///  </ Summary> 
        ///  <Returns> </ Returns> 
        public  BOOL the IsEmpty () 
        { 
            return top == - . 1 ? to true : to false ; 
        } 

        ///  <Summary> 
        /// popped from the top of the stack pop data
         ///  </ Summary> 
        ///  <Returns> </ Returns> 
        public  int pop ( ) 
        { 
            IF (the IsEmpty ()) 
            { 
                return - . 1; 
            } 
            The else 
            { 
                // the data is first ejected, and then the stack pointer down 
                return Stack [top-- ]; 
            } 
        } 
    } 
}

In the Main method call:

using System;

namespace StackByArray
{
    class Program
    {
        static void Main(string[] args)
        {
            int value;
            StackArray stack = new StackArray(10);
            Console.WriteLine("按顺序输入10个数:");
            for (int i = 0; i < 10; i++)
            {
                value = int.Parse(Console.ReadLine());
                // 入栈
                stack.Push(value);
            }
            Console.WriteLine("=================");
            while(!stack.IsEmpty())
            {
                Console.WriteLine($"堆栈弹出顺序:{stack.Pop()}");
            }

            Console.ReadKey();
        }
    }
}

Program output:

Third, to implement a stack using a linked list

Although the benefits to an array of structures to create the stack is to produce and design algorithms are quite simple, but if the stack itself is a change, then the array size can not be planned in advance statement. At this point we tend to consider the possibility of using an array of maximum space, but it will be a waste of memory space, and the advantages of using the list to make the stack is ready to be dynamically change the length of the list, but the drawback is that the design of the algorithm is more complicated. Here we use a linked list to implement a stack.

Node node class:

namespace StackByLinked
{
    /// <summary>
    /// 节点
    /// </summary>
    public class Node
    {
        public int Data { get; set; }

        public Node Next { get; set; }

        public Node(int data)
        {
            Data = data;
            Next = null;
        }
    }
}

堆栈类:

using System;

namespace StackByLinked
{
    public class StackLinked
    {
        // 定义指向堆栈底端的指针
        public Node Front;
        // 定义指向堆栈顶端的指针
        public Node Rear;

        /// <summary>
        /// 判断堆栈是否为空堆栈
        /// </summary>
        /// <returns></returns>
        public bool IsEmpty()
        {
            return Front == null;
        }

        /// <summary>
        /// 打印输出堆栈的内容
        /// </summary>
        public void Print()
        {
            Node current = Front;
            while(current!=null)
            {
                Console.Write(current.Data + " ");
                current = current.Next;
            }
            Console.WriteLine();
        }

        /// <summary>
        /// 入栈
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public void Push(int data)
        {
            Node newNode = new Node(data);
            if(IsEmpty())
            {
                Front = newNode;
                Rear = newNode;
            }
            else
            {
                Rear.Next = newNode;
                Rear = newNode;
            }
        }

        /// <summary>
        /// 出栈 返回栈顶元素
        /// </summary>
        /// <returns></returns>
        public int Pop()
        {
            Node newNode;
            if(IsEmpty())
            {
                Console.WriteLine("当前为空队列");
                return -1;
            }
            newNode = Front;
            if(newNode == Rear)
            {
                Front = null;
                Rear = null;
                Console.WriteLine("当前为空队列");
                return -1;
            }
            else
            {
                while(newNode.Next!=Rear)
                {
                    newNode = newNode.Next;
                }
                int value = Rear.Data;
                // newNode被null赋值,相当于移除了Rear
                newNode.Next = Rear.Next;
                Rear = newNode;
                return value;
            }
        }
    }
}

Main方法调用:

using System;

namespace StackByLinked
{
    class Program
    {
        static void Main(string[] args)
        {
            StackLinked stack = new StackLinked();
            int choice = 0;
            while(true)
            {
                Console.Write("0结束 1把数据加入堆栈 2从堆栈弹出数据:");
                choice = int.Parse(Console.ReadLine());
                if(choice==2)
                {
                    int value= stack.Pop();
                    Console.WriteLine($"弹出的栈顶元素:{value}");
                    Console.WriteLine("数据弹出后堆栈中的内容");
                    stack.Print();
                }
                else if(choice == 1)
                {
                    Console.WriteLine("请输入要加入堆栈的数据:");
                    choice = int.Parse(Console.ReadLine());
                    stack.Push(choice);
                    Console.WriteLine("数据加入后堆栈中的内容:");
                    stack.Print();
                }
                else if(choice == 0)
                {
                    break;
                }
                else
                {
                    Console.WriteLine("输入错误");
                }
            }

            Console.ReadKey();
        }
    }
}

程序运行结果:

Guess you like

Origin www.cnblogs.com/dotnet261010/p/12324551.html