编程语言
首页 > 编程语言> > 链栈(C++实现)

链栈(C++实现)

作者:互联网

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 using namespace std;
 5 typedef struct Stack{
 6     struct Stack *next;
 7     int data;
 8 }*LinkedStack,Node;
 9 void LinkedStack_Empty(LinkedStack &top){
10     top = (Node*)malloc(sizeof(Node));
11     if(top == NULL){
12         cout<<"申请空间失败"<<endl;
13         return ; 
14     }
15     top->next = NULL;
16     cout<<"创建空栈成功(带头节点)!"<<endl; 
17 }
18 //判断栈是否为空
19 bool isEmpty(LinkedStack top){
20     return top->next == NULL;
21 }
22 //入栈
23 void push(LinkedStack &top,int num){
24     Node *new_Node = (Node*)malloc(sizeof(Node));
25     if(new_Node == NULL){
26         return ;
27     }
28     new_Node->data = num;
29     new_Node->next = top->next;
30     top->next = new_Node;
31 } 
32 //出栈
33 void pop(LinkedStack &top){
34     if(isEmpty(top) == true){
35         cout<<"出栈失败,为空栈"<<endl;
36         return ; 
37     }
38     Node *del = top->next;
39     top->next = del->next;
40     free(del);
41 } 
42 void display(LinkedStack top){
43     if(isEmpty(top)==true){
44         cout<<"空栈"<<endl;
45     }
46     else{
47         Node *temp = top;
48         temp = temp->next;
49         while(temp != NULL){
50             cout<<temp->data<<" ";
51             temp = temp->next;
52         }    
53     }
54     cout<<endl;
55 }
56 int main(){
57     LinkedStack stack;
58     LinkedStack_Empty(stack);
59     for(int i = 1;i<=10;i++){
60         push(stack,i);
61     }
62     display(stack);
63     for(int i = 1;i<=10;i++){
64         pop(stack);
65         display(stack);
66     }
67     return 0;
68 }

 

标签:Node,实现,top,C++,next,链栈,LinkedStack,new,NULL
来源: https://www.cnblogs.com/whtmomo/p/14143220.html