#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
} Node;
typedef struct stack{
Node* top;
Node* bottom;
int count;
} *Stack;
void InitStack(Stack &S){
S = (Stack)malloc(sizeof(stack));
S->bottom = NULL;
S->top = NULL;
S->count = 0;
}
void Push(Stack &S,int num){
Node *stone;
stone = (Node*)malloc(sizeof(Node));
stone->data = num;
stone->next = S->top;
S->top = stone;
S->count++;
if(S->bottom == NULL){
S->bottom = S->top;
}
}
void Dispaly(Stack S){
printf("遍历栈:\n");
Node* p = (Node*)malloc(sizeof(Node));
p = S->top;
if(S->count==0){
printf("栈中没有数据\n");
}
for(int i = 0;i<S->count;i++){
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int Pop(Stack S){
int elem;
Node* p = (Node*)malloc(sizeof(Node));
p = S->top;
elem = p->data;
S->top = p->next;
S->count--;
free(p);
return elem;
}
int getTop(Stack S){
int elem;
Node* p = (Node*)malloc(sizeof(Node));
p = S->top;
elem = p->data;
return elem;
}
main(){
Stack S;
InitStack(S);
int num,i,x;
printf("随机生成10个数并且入栈:\n");
for(i = 0;i<10;i++){
num = rand()%100+1;
printf("%d ",num);
Push(S,num);
}
printf("\n");
Dispaly(S);
num = Pop(S);
printf("弹出栈顶元素:%d\n",num);
Dispaly(S);
num = getTop(S);
printf("读出栈顶元素:%d\n",num);
Dispaly(S);
}
实现链栈(进栈、出栈、读栈、初始化)
于 2022-07-01 10:11:07 首次发布