C # Advanced Object-oriented programming (I.)--Implementation stack

Source: Internet
Author: User

How do I write a stack class in C #?

The key is how should such a class be designed? First of all, we must establish the object-oriented programming idea, that is, the class is to reasonably abstract and model the entity, and this thought will be carried out throughout our programming process. Let's do it one step at a to the next.

1. Preliminary design of class method signature

For the design of a class we should design from the outside, first consider its external interface, and then consider its internal arrangements. For the stack, the most important external feature is the compression stack and the stack, so to design two methods push and pop, for the compression stack, where the pressed elements are stored, so we need to use an array to open a contiguous storage space to store the stack sequentially. So the preliminary design is as follows:

 public  class   Stack  { private  int  [] array = new  int  [3  ];  public  void  Push (int   element) {}  public int   Pop () { return  0  ; }    }  

How should the concrete approach be implemented? We know that the stack and the stack are all at the top of the stack, how to represent the top of the stack? We can set a counter cout to count each stack operation, also count the stack operation, so that the counter always represents the number of elements in the stack. So add the relevant statement in the previous code, and now the code is as follows:

     Public classStack {Private int[] Array =New int[3]; Private intcount;  Public voidPush (intElement) {Count++; }         Public intPop () {count--; return 0; }    }  

Then we will implement the functions of the two methods separately.

 public  void  Push (int   element) { this . ar            Ray[this . Count] = ++;  public  int   Pop () { int  ele = this.array[this . Count-1  ];            Count --;         return   Ele; }

At this point, the functionality of the two methods has been basically implemented.

2. Design derivation-using anomaly mechanisms, taking into account boundary conditions

Now there is a problem, that is, the stack of storage space is fixed with an array of allocations, then the stack may be full overflow after the situation. In order to deal with this abnormal situation we need to take appropriate measures. Similar stacks can also appear in the case of stack empty. Let's start with the latter:

         Public intPop () {if( This. Count = =0)            {                Throw NewException ("the stack is already empty! "); }            intEle = This. array[ This. Count-1]; -- This. Count; returnEle; }

We then add the Try-catch statement to the test method to handle the thrown exception.

And for the push method, how do we want to append the storage space when the stack is full?

We then define an array that opens up twice times the contiguous storage space of the original array, then copies the elements from the original array to the new array, and assigns the new array's references to the original array for external use.

         Public voidPush (intElement) {            if( This. Count = = This. Array. Length) {int[] Array2 =New int[ This. Array. Length *2];  for(inti =0; I < This. Array. Length; i++) {Array2[i]=Array[i]; }                 This. Array =array2; }                 This. array[ This. Count] =element;  This. count++; }

In this way, the class has been basically designed.

3. Functional Testing

Add the following test code to the Main method:

        Static voidMain (string[] args) {            Try{Stack stack=NewStack (); Stack. Push (2); Stack. Push (5); Stack. Push (8); Stack. Push (9); intEle1 =stack.                Pop (); Console.WriteLine ("{0}", Ele1); intEle2 =stack.                Pop (); Console.WriteLine ("{0}", Ele2); intEle3 =stack.                Pop (); Console.WriteLine ("{0}", Ele3); intEle4 =stack.                Pop (); Console.WriteLine ("{0}", ele4); }            Catch(Exception Exception) {Console.WriteLine ("execution error occurred! "+exception.            Message);        } console.read (); }

The results of the operation are as follows:

C # Advanced Object-oriented programming (I.)--Implementation stack

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.