Stack structure establishment and operations in C ++

Source: Internet
Author: User

What is stack structure?

The stack structure is classified by data operations. That is to say, the stack structure has special operation rules, that is, back-to-first-out.

We can think of the stack as a large warehouse. Goods placed at the warehouse door (the top of the stack) will be taken out first and then the goods in the warehouse will be taken out.

From the logic structure of the data, the stack structure starts with a linear structure.

If we further divide the data storage structure, the stack structure includes two types:

Sequence stack structure:

That is, the data in the stack is saved in sequence using a group of memory units with consecutive addresses. In a program, you can define an array of the specified size as a stack. The element with the serial number 0 is the low stack. Then, you can define a variable top to save the serial number at the top of the stack.

Chain stack structure:

Saves the values of each element in the stack in the form of a linked list. The head of the linked list (the head Pointer Points to the element) is the top of the stack, and the tail of the linked list (pointing to the address is NULL) is the bottom of the stack.

 

In the stack structure, operations can only be performed at one end. The operation end is called the stack top and the other end is called the stack bottom. That is to say, the stored and retrieved data can only be performed from one end of the stack structure. From the perspective of Data calculation, the stack structure processes the node data according to the "first-in-first-out" principle.

In the stack structure, only the top elements of the stack can be accessed, and the data operation of the stack structure is also very simple. Generally, there are only two basic operations on the stack structure:

Push: the operation of saving data to the top of the stack. Before the stack entry operation, modify the stack top pointer to move it up to an element position and save the data to the position indicated by the stack top pointer.

Pop: The operation that pops up the top data of the stack. Modify the stack top pointer so that it points to the next element in the stack.

Next, we use the C ++ language to establish the sequence stack and complete the basic operation of the sequence stack structure.

Prepare data

Prepare the variables and data structures required for Stack operations.

 

#define MAXLEN 50struct DATA{string name;int age;};struct StackType{DATA data[MAXLEN+1];int top;};
Defines the length of the stack structure MAXLEN, the DATA element type DATA of the stack structure, and the DATA structure StackType of the stack structure. In the data structure StackType, data is the data element, and top is the serial number at the top of the stack. When top = 0, the stack is empty. When top = MAXLEN, the stack is full.

Array elements start with a subscript of 0. Here we record the data node from subscript 1 for ease of illustration and understanding. The position of subscript 0 is not needed.

Initialize stack structure

Before using the stack structure, you must first create an empty sequence stack, that is, initialize the sequence stack. The initialization of the sequence stack is as follows:

(1) apply for a memory space according to the size specified by the symbolic constant MAXLEN to save data in the stack.

(2) set the value of the stack top pointer to 0, indicating an empty stack.

The sample code is as follows:

StackType * STInit () {StackType * p; if (p = new StackType) // apply for stack space {p-> top = 0; // set the stack top to 0 return p; // return stack top pointer} return NULL ;}

First, use new to apply for memory, set the stack top to 0, then return the first address of the applied memory, and return NULL if the application fails;

Judge empty Stack

Check whether the stack structure is empty. If the stack structure is empty, it indicates that there is no data in the stack structure. In this case, you can perform inbound stack operations, but you cannot perform outbound stack operations.

The sample code is as follows:

Int STIsEmpty (StackType * s) {int t; t = (s-> top = 0); // return t is determined by the value at the top of the stack ;}

The input parameter s is a pointer to the stack of the operation. Judge whether the top pointer of the stack is 0 and whether the stack is empty.

Judge full Stack

Determine whether the stack structure is full. If the stack is full, there is no extra space in the stack structure to store additional data. At this time, you cannot perform the stack import operation, but you can perform the stack import operation.

The sample code is as follows:

int STIsFull(StackType *s){int t;t=(s->top==MAXLEN);return t; }

The input parameter s is a pointer to the stack of the operation. Based on the top pointer of the stack, determine whether the stack is equal to MAXLEN and whether the stack is full.


Clear Stack

Stack clearing means all data in the stack is cleared. The sample code is as follows:

void STClear(StackType *s){s->top=0;} 

Set the top pointer of the stack to 0, indicating that the stack is cleared. (Data in the stack is cleared logically. In fact, the top is set to 0. Adding data later will overwrite the original data)

Release Space

The space to be released is the memory unit occupied by the stack structure. delete is used to release the memory space applied for by the new operator.

The sample code is as follows:

void STFree(StackType *s){delete s;} 

Call the delete operator in a program to release the allocated memory space. This function is generally called when the stack structure is not required, especially when the program ends.

Inbound Stack

Push is the basic operation of the stack structure. The main operation is to save data elements to the stack structure. Perform the following operations:

(1) first judge the top stack. If the top is greater than or equal to MAXLEN, it indicates overflow and error handling. Otherwise, perform the following operations.

(2) Set top = top + 1 (stack top pointer plus 1, pointing to the inbound stack address)

(3) Save the inbound urea to the top point.

The sample code is as follows:

Int PushST (StackType * s, DATA data) {if (s-> top + 1)> MAXLEN) {cout <"stack overflow" <endl; return 0 ;} s-> data [++ s-> top] = data; // press the element into the stack and return 1 ;}

The input parameter s is a pointer to the operation stack. The input parameter data is the data element to be imported into the stack. The program first checks whether the stack overflows. If the stack overflows, a warning is given. If the stack overflow occurs, no inbound operations are performed. Otherwise, the top pointer of the stack is modified, that is, top is first added with 1, then place the data to the data unit currently pointed to by the top node.

Outbound Stack

Pop is the basic operation that occupies the dog. The main operation is opposite to the inbound operation. It is a data element popped up from the top of the stack. The specific steps for the outbound operation are as follows:

(1) first, judge the top of the stack. If top is equal to 0, it indicates where the fear is, and handle the error. Otherwise, perform the following operations.

(2) return the element at the position pointed to by the top pointer of the stack (actually the returned pointer)

(3) subtract 1 from the top and point to the next element of the stack. The element at the top of the stack is popped up.

DATA * PopST (StackType * s) {if (s-> top = 0) {cout <"the stack is empty and cannot be output any more! "<Endl; exit (0);} return & (s-> data [s-> top --]);}

When there is DATA in the stack, the return value of this function is a pointer to DATA type DATA.

Read point structure

The reading point structure refers to reading the data of nodes in the stack structure. Since the stack structure can only be operated at one end, the read operation here is actually to read the data of the site.

Note that the operations on reading node data are different from those on the outbound stack. The read node operation only displays the data of the top node of the stack, and the output stack operation pops up the top data of the stack.

The sample code is as follows:

DATA * PeekST (StackType * s) {if (s-> top = 0) {cout <"Stack empty" <endl; exit (0 );} return & (s-> data [s-> top]);}

Comparing the stack sample code, it is not difficult to find that the address of the top node of the stack is returned in the reading point structure, but the top node is not reduced by 1.

Complete example

The following is a complete example of the basic stack operations:

Program code:

# Include <iostream> # include <string> using namespace std; # define MAXLEN 50 struct DATA {string name; int age ;}; struct StackType {DATA data [MAXLEN + 1]; int top ;}; /****************** initialize the stack structure *****************/StackType * STInit () {StackType * p; if (p = new StackType) // apply for stack space {p-> top = 0; // set the stack top to 0 return p; // return stack top pointer} return NULL ;} ******************** **/int STIsEmpty (StackType * s) {int t; t = (s-> top = 0); // pass Return t ;} /********************** determine full stack ************** **/int STIsFull (StackType * s) {int t; t = (s-> top = MAXLEN); return t ;} /********************** clear the stack *************** * ******/void STClear (StackType * s) {s-> top = 0 ;} /********************* release space ***************** * **/void STFree (StackType * s) {delete s ;} *************** * ******/int PushST (StackType * s, DATA data) {if (s-> top + 1)> MAXLEN) {Cout <"stack overflow" <endl; return 0;} s-> data [++ s-> top] = data; // push elements into Stack return 1 ;} ************* * *********/DATA * PopST (StackType * s) {if (s-> top = 0) {cout <"Stack is empty and cannot be output any more! "<Endl; exit (0);} return & (s-> data [s-> top --]);} ************** */DATA * PeekST (StackType * s) {if (s-> top = 0) {cout <"Stack empty" <endl; exit (0 );} return & (s-> data [s-> top]);} /**************** go to the main function ******************* * **/int main () {StackType * stack; DATA data, * p_data; stack = STInit (); cout <"================= inbound stack operation: ============== "<endl; cout <" enter the name and age for the stack import operation: "<endl; // execute the inbound operation while (1) {cin> data. name> data. age; if (data. name = "0") {break; // exit the input when the name and age are both 0} else {PushST (stack, data );}} p_data = PopST (stack); cout <"top stack elements" <endl; cout <"name:" <p_data-> name <", age: "<p_data-> age <endl; p_data = PeekST (stack); cout <" output stack top element "<endl; cout <" name: "<p_data-> name <", age: "<p_data-> age <endl; cout <"==================== export all data out of the stack: ============ "<endl; while (1) {p_data = PopST (stack); cout <" name: "<p_data-> name <", age: "<p_data-> age <endl;} STFree (stack); return 0 ;}

Program running interface:



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.