#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define SIZE 10
// 数据域
typedef struct LData {
int c; // 常数
} LData;
// 单链表
typedef struct SNode {
LData data; //数据域
struct SNode *next;
} SNode;
// 初始化栈
SNode *InitStack(){
SNode *s;
s = (SNode *) malloc(SIZE* sizeof(SNode));
s->next = NULL;
return s;
}
//入栈
void push(SNode **s, int e){ // 头结点为栈顶
if((*s) == NULL){
printf("栈不存在\n");
}
SNode *p; // 创建新节点,作为头结点
p = (SNode *) malloc(sizeof(SNode));
p->data.c = e; // 给新节点赋值
p->next = (*s); // 新节点的下一个就是原头结点的下一个
(*s) = p; // 将新节点的地址给原头结点
}
// 出栈
void pop(SNode **s){
if((*s)->next == NULL){
printf("pop栈为空\n");
return;
}
SNode *p;
p = (*s); // p保存的是头结点
printf("出栈元素为:%d\n", (*s)->data.c);
(*s) = p->next; // 将头结点的下一个节点作为头结点
free(p); // 释放出栈节点
}
// 清空栈
void clearStack(SNode **s){
if((*s)->next == NULL){
printf("clearStack栈为空\n");
return;
}
SNode *p;
while ((*s)->next != NULL){
p = (*s);
(*s) = (*s)->next;
free(p);
}
printf("已清空\n");
}
// 销毁栈
void destroyStack(SNode **s){
if((*s) == NULL){
printf("destroyStack栈为空\n");
return;
}
SNode *p;
while ((*s)->next != NULL){
p = (*s);
(*s) = p->next;
free(p);
}
(*s) = (*s)->next;
free((*s));
printf("已销毁\n");
}
//获取栈的长度
void getStackLength(SNode **s){
if((*s) == NULL){
printf("栈为空\n");
return;
}
int count = 0;
SNode *p;
p = (*s);
while (p->next != NULL){
count++;
p = p->next;
}
printf("栈的长度为:%d\n", count);
}
int main() {
//测试
SNode *s;
s = InitStack();
push(&s, 1);
push(&s, 2);
push(&s, 3);
push(&s, 4);
getStackLength(&s);
pop(&s);
pop(&s);
clearStack(&s);
pop(&s);
pop(&s);
destroyStack(&s);
push(&s, 4);
return 0;
}
链表实现栈、入栈、出栈、栈的长度、销毁栈、清空栈
最新推荐文章于 2024-05-20 20:48:02 发布