栈的C++实现(指针)——创建-push-pop-top-清空栈-处理栈
今天学习了栈的C++实现,跟单链表很像:
push相当于单链表在第一个位置插入元素;
pop相当于单链表在第一个位置删除元素;
1、空栈检查
1 int stack::isEmpty(Stack *S) 2 { 3 return S->next == NULL; 4 }
2、创建一个空栈
1 stack::Stack *stack::createStack() 2 { 3 Stack *S; 4 S = (Stack*)new(Stack); 5 //栈空间满后,溢出 6 if (S == NULL) 7 cout << "Out of space! " << '\n'; 8 S->next = NULL; 9 makeEmpty(S); 10 return S; 11 }
空栈只有头结点,第9行表示若不为空栈则删除除头结点以外的所有结点。
3、清空栈(保留头结点)
1 void stack::makeEmpty(Stack *S) 2 { 3 if (isEmpty(S)) 4 cout << "Donnot need to makeEmpty!" << '\n'; 5 else 6 while (!isEmpty(S)) 7 pop(S); 8 }
4、push操作
1 stack::Stack *stack::push(int x, Stack *S) 2 { 3 Stack *tem; 4 tem = (Stack*)new(Stack); 5 if (tem == NULL) 6 { 7 cout << "Out of space! " << '\n'; 8 } 9 else 10 { 11 cout << "please input the data to push: " << '\n'; 12 13 scanf_s("%d",&x); 14 15 tem->Data = x; 16 tem->next = S->next; 17 S->next = tem; 18 return S; 19 } 20 }
5、top操作
1 int stack::top(Stack *S) 2 { 3 if (isEmpty(S)) 4 { 5 cout << "Empty stack! " << '\n'; 6 return -1; 7 } 8 else 9 return S->next->Data; 10 }
6、pop操作(释放第一个结点后,显示该结点的数据元素)
1 stack::Stack *stack::pop(Stack *S) 2 { 3 Stack *p; 4 p = NULL; 5 if (isEmpty(S)) 6 cout << "Empty stack! " << '\n'; 7 else 8 { 9 p = S->next; 10 cout << "the Data be poped is : " << p->Data << endl; 11 S->next = p->next; 12 free(p); 13 return S; 14 } 15 }
7、处理栈(删除包括头结点)
1 void stack::disposeStack(Stack *S) 2 { 3 if (S == NULL) 4 cout << "Donnot need to disposeStack! " << '\n'; 5 while (!isEmpty(S)) 6 pop(S); 7 free(S); 8 }
8、主函数
1 int main() 2 { 3 cout << '\n' << "***************************************" << '\n' << '\n'; 4 cout << "Welcome to the stack world! " << '\n'; 5 cout << '\n' << "***************************************" << '\n' << '\n'; 6 7 int i = 1; 8 int j = 0; 9 int topElement = 0; 10 stack *a = new stack; 11 stack::Stack *S = NULL; 12 int x = 0; 13 while (i) 14 { 15 cout << '\n' << "***************************************" << '\n'; 16 cout << " 0 : end the stack " << '\n'; 17 cout << " 1 : creat a stack " << '\n'; 18 cout << " 2 : display the top element of stack " << '\n'; 19 cout << " 3 : push a node in the stack " << '\n'; 20 cout << " 4 : pop a node from the stack " << '\n'; 21 cout << "***************************************" << '\n'; 22 cout << "Please input the function your want with the number above : " << '\n'; 23 scanf_s("%d", &j); 24 25 switch (j) 26 { 27 case 1: 28 cout << "CreatStack now begin : "; 29 S = a->createStack(); 30 break; 31 case 2: 32 topElement = a->top(S); 33 cout << "The top element of stack is : " << topElement; 34 break; 35 case 3: 36 cout << "push now begin : "; 37 S = a->push(x, S); 38 break; 39 case 4: 40 cout << "pop now begin : "; 41 S = a->pop(S); 42 break; 43 default: 44 cout << "End the stack. "; 45 a->disposeStack(S); 46 i = 0; 47 break; 48 } 49 50 } 51 }
运行结果: