I. Finishing touches 1. What is a sequential stack?
For the concept of stacks, refer to the article implementation of the collection Framework (11): Stack interface definition, then what is the sequential stack? Sequential stacks are stacks that store data elements in sequential storage structures, such as arrays to hold data elements. Stack has its inherent characteristics: only on the top of the stack operation, LIFO and so on. So what happens to the sequence stack and its state when the data elements are in the stack?
For example, the data element to manipulate is a a,b,c,d of four elements, and the action is:
You'll be on the stack--and on the stack--and on the stack--and out--and out the stack.
The state of the stack changes as shown in the following diagram:
two. Sequential stack implementation 1. Define the sequence stack
The sequential Stack class Seqstack implements the stack interface Sstack, and implements the method defined in the stack interface, the definition of the stack interface refers to the previous article to implement the set Framework (11): The Stack interface definition, the code is as follows:
Code Explanation:
1. Define two constructors, a parameterless constructor, the capacity of the stack defaults to 16, and the other has a parameter constructor, you can specify the capacity of the stack.
2. Math.Abs (capacity) Take the absolute value of the stack capacity, do fault-tolerant processing, to prevent the case of negative. 2. Determine if the stack is empty
Code Explanation:
The criteria for determining whether the stack is empty is based on whether the index top element of the stack is 1. 3. Into the stack
4. The Stack
5. Take the top element of the stack
6. Overriding the ToString () method
Code Explanation:
Returns the string representation of each element in the stack, starting at the top of the stack and ending at the bottom of the stack. three. Testing
The result of the operation is shown in the following figure:
Four. Time complexity analysis
Since the stack can only be inserted and deleted at the top of the stack, the time complexity of the stack push (), the stack pop () and the get stack top element get () is O (1), and when the capacity needs to be expanded, the time complexity of the push () of the stack operation is O (n). Five. Source code example