4-栈-链式存储
笔记
栈-链式存储
使用链表的方式存储栈的指针数据,将栈顶设置在链表头部
入栈就相当于头插、出栈相当于头删
size记录栈的大小,数据预留出4字节用来存储指针
代码
myStack.c
#include"myStack.h"
#include<stdlib.h>
//使用链表的方式存储栈的指针数据,将栈顶设置在链表头部
//入栈就相当于头插、出栈相当于头删
//初始化管理栈的结构体
myStackType* init_stack(){
myStackType* st = malloc(sizeof(myStackType));
if(NULL == st){
return NULL;
}
st->head.next = NULL; //清零
st->m_size = 0;
return st;
}
//入栈
void push_stack(myStackType* st, void* data){
if(NULL == st || NULL == data){
return;
}
struct linkNode* myNode = data; //将数据指针转换成节点类型,使用data预留的4字节
myNode->next = st->head.next; //头插
st->head.next = myNode;
st->m_size++;
}
//出栈
void pop_stack(myStackType* st){
if(NULL == st){
return;
}
if(st->m_size == 0){
return;
}
struct linkNode* delNode = st->head.next; //头删
st->head.next = delNode->next;
st->m_size--;
}
//获取栈顶数据
void* top_stack(myStackType* st){
if(NULL==st || st->m_size==0){
return NULL;
}
return st->head.next; //即链表的第一个元素
}
int size_stack(myStackType* st){
if(NULL == st){
return 0;
}
return st->m_size;
}
//销毁栈结构体
void destroy_stack(myStackType** st){
free(*st);
*st = NULL;
}
myStack.h
#ifndef __MYSTACK_H
#define __MYSTACK_H
struct linkNode{
void* next;
};
typedef struct {
struct linkNode head;
int m_size;
}myStackType;
myStackType* init_stack(void);
void push_stack(myStackType* st, void* data);
void pop_stack(myStackType* st);
void* top_stack(myStackType* st);
int size_stack(myStackType* st);
void destroy_stack(myStackType** st);
#endif
start0.c
#include"myStack.h"
#include<stdio.h>
struct Persion{
void* next;
char m_name[64];
int m_age;
};
int main(){
myStackType* st = init_stack();
struct Persion p1 = {NULL,"aaa",10};
struct Persion p2 = {NULL,"bbb",20};
struct Persion p3 = {NULL,"ccc",30};
struct Persion p4 = {NULL,"ddd",40};
push_stack(st,&p1);
push_stack(st,&p2);
push_stack(st,&p3);
push_stack(st,&p4);
printf("size=%d\n",size_stack(st));
while(size_stack(st) > 0){
struct Persion *p0 = top_stack(st);
pop_stack(st);
printf("name=%s\tname=%d\n",p0->m_name, p0->m_age);
}
printf("size=%d\n",size_stack(st));
destroy_stack(&st);
return 0;
}