[Translation] C # data structures and algorithms-Chapter 5 stack and queue (Part 1)

Source: Internet
Author: User

The5Chapter Stack and queue

It is natural to organize data in a list. Previously, we used Array and ArrayList to organize data as lists. Although these data structures help us organize data in a suitable format for processing, there is no structure that provides a realistic abstraction to design and implement a solution to the problem.

Stack and queue are two types of list-oriented data structures, which provide easy-to-understand abstraction. The data in the stack is added and removed by one end of the list, while the data in the queue is added by one end of the list and removed by the other end of the list. Stack is widely used in programming language implementation, from expression evaluation to function calling. Queues are used to handle the priority calls of operating system processes and simulate the occurrence of events in the world, such as the cashier of a bank and elevator operations in a building.

C # provides two classes to use these two data structures: Stack class and Queue class. We will discuss how to use these classes and take a look at some practical examples in this chapter.

STACK, STACK implementation and STACKClass

Stack is the most commonly used data structure, as we just mentioned. We define a stack as a list of projects, which can only be accessed at the end of the list. This tail is called the top of the stack. The standard mode of a stack is like a pile of meals in a cafeteria. The plate is always taken from a pile of top. When the worker or waiter puts the plate back, it is still put back to the top. Stack is a data structure called LIFO.

Stack operations

The two major operations of stack are to add items to stack and remove items from Stack. The Push operation adds an item to the stack, and the Pop operation removes an item from the stack. Figure 5.1 shows these operations.

Another major operation on the stack is to view the top element. Although the Pop operation returns the top element, this operation also removes the element from the top of the stack. We only need to check the top element without removing it. In C #, the operation name is Peek. In other languages or implementations, the name may be different (for example, Top ).

Push, Pop, and Peek are the main operations we perform when using stacks. At the same time, there are many other methods and attributes that require us to learn and try to operate. It is useful to remove all items from one stack at a time. You can call the Clear operation to completely Clear a stack. It is also useful to obtain the number of items in the stack at any time. You can call the Count attribute to achieve this purpose. Many operations determine the stack status through a StackEmpty method that returns true or false. We can also use the Count attribute to achieve the same purpose.

. The Stack class in the NET Framework implements the above mentioned and more attributes and methods, but before we learn how to use the Stack, let's first understand if there is no Stack class, how can we implement a stack.

Implementation of a stack class

The implementation of a stack requires the use of the underlying data structure to store data. We will select ArrayList. Because of this, we don't have to worry about adjusting the size of the list when a new item is added to the stack.

Because C # has excellent Object-Oriented Programming features, we implement this stack as a class called CStack. In this class, we will implement a constructor. The methods mentioned above and the Count attribute will demonstrate how to complete this job in C.

First, let's implement the private data members required in this class.

The most important variable in this class is an ArrayList object used to store stack projects. The only other data we need to trace is the top of the stack. We will use a simple integer variable as an index. This variable is set to-1 during initialization of A CStack object. Every time a project is pushed into the stack, this variable is increased by 1.

The constructor does not perform any work except initialize the index variable-1. The first method to be implemented is Push. Its code calls the Add method of ArrayList to pass the value to be added to ArrayList. The Pop method completes three tasks: first call the RemoveAt method to obtain the elements at the top of the stack (removed from the ArrayList), subtract 1 from the index value, and finally return the stack object.

The implementation of the Peek method can obtain the required value through the Item indexer and using the index variable as the parameter. The Clear method calls the method of moderate price in the ArrayList class. The Count attribute is implemented as a read-only attribute, because we do not want to accidentally change the number of items in the stack.

The complete code is as follows:

Class CStack

{

Private int p_index;

Private ArrayList list;

Public CStack ()

{

List = new ArrayList ();

P_index =-1;

}

Public int count

{

Get {return list. Count ;}

}

Public void push (object item)

{

List. Add (item );

P_index ++;

}

Public object pop ()

{

Object obj = list [p_index];

List. RemoveAt (p_index );

P_index --;

Return obj;

}

Public void clear ()

{

List. Clear ();

P_index =-1;

}

Public object peek ()

{

Return list [p_index];

}

}

Next, let's use this code to complete a program that uses the stack to solve the problem.

A forward and reverse spelling character strings. For example, "dad", "madam", and "sees" are both input files, while "hello" is not input files. Stack is used to check whether a string is input. The general algorithm is to read strings one by one and store each character as a stack during reading. This achieves a reverse Saving Effect for string characters. The next step is to take each character out of the stack and compare the corresponding characters starting from the original string. If the two characters are different at any position, the program can stop if the string is not a background. If the comparison can be performed from the beginning to the end, this string is a background.

The following is a program that lists only the Main function, because we have defined the CStack class:

Static void Main (string [] args)

{

CStack alist = new CStack ();

String ch;

String word = "sees ";

Bool isPalindrome = true;

For (int x = 0; x <word. Length; x ++)

Alist. push (word. Substring (x, 1 ));

Int pos = 0;

While (alist. count> 0)

{

Ch = alist. pop (). ToString ();

If (ch! = Word. Substring (pos, 1 ))

{

IsPalindrome = false;

Break;

}

Pos ++;

}

If (isPalindrome)

Console. WriteLine (word + "is a palindrome .");

Else

Console. WriteLine (word + "is not a palindrome .");

Console. Read ();

}

StackClass

A Stack class is a collection class/Stack that implements the ICollection interface of LIFO .. The Stack class in the NET Framework is implemented as a circular buffer, which allows the space required by stack items to be dynamically allocated.

The Stack class contains methods used to get the top values of the Stack. It also provides methods to obtain the attribute of the meta-prime number in the stack, clear the stack's median, and convert the stack to an array. First, we will study the constructor of the Stack class.

StackClass Constructor

There are three methods to initialize a Stack object. The default constructor initializes an empty stack and initializes the Capacity attribute to 10. The default constructor is called as follows:

Stack myStack = new Stack ();

A generic stack is initialized as follows:

Stack <string> myStack = new Stack <string> ();

Each time the number of elements in the stack reaches the maximum stack capacity, the capacity will be doubled.

The second constructor of Stack allows you to create a Stack object from another collection object. For example, you can pass an array to the constructor, and a stack will be created by an existing array element:

String [] names = newstring [] {"Raymond", "David", "Mike "};

Stack nameStack = new Stack (names );

Executing the Pop method will first remove "Mike" from the stack ".

You can also specify the initial capacity of the stack while initializing a stack object. This constructor can be used when you know in advance how many elements are to be stored in the stack. If you build your stack in this way, you can make your program more efficient. If your stack has 20 elements and has reached the maximum capacity, adding a new element will trigger 20 + 1 operation, because each element needs to be moved to adapt to the new element.

The code for specifying the initial size when initializing the stack is as follows:

Stack myStack = new Stack (25 );

Stack operations

The main operations performed on the stack are Push and Pop. Use the Push method to import data to the stack. Use the Pop method to complete the data output stack operation. Let's learn these methods in the problematic environment of using a simple arithmetic expression of stack computing.

The expression evaluate program uses two stacks, one for the operands and the other for the operators. An arithmetic expression is stored as a string. By using the for loop to read each character in the expression, we analyze the string as a separate symbol. If the symbol is a number, place it in the digital stack. If the symbol is an operator, place it into the operator stack. Because we execute the infix expression, we need to wait for the two operands to be completed before performing an operation. At this moment, we take the two operands out of the stack and execute the specified arithmetic operation. The result is re-written into the stack as the first expression for the next calculation. This process continues until we complete the inbound and outbound operations on all the numbers.

The following code is used:

Using System;

Using System. Collections;

Using System. Text. RegularExpressions;

Namespace csstack

{

Class Class1

{

Static void Main (string [] args)

{

Stack nums = new Stack ();

Stack ops = new Stack ();

String expression = "5 + 10 + 15 + 20 ";

Calculate (nums, ops, expression );

Console. WriteLine (nums. Pop ());

Conso

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.