一、栈(stack)的基础知识
栈也是数据结构的一种,与队列不同的是栈是一种后进先出(LIFO-last input frist output)的数据结构(队列详解),其具体的结构特点如下图所示:
二、用C语言实现一个栈(stack)
整体代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
typedef struct {
uint8_t id;
} USER_DATA_T;
typedef struct stack{
struct stack *next;
USER_DATA_T data;
} STACK_T;
STACK_T *head_stack = NULL; //栈头节点指针
STACK_T *stack_init(void)
{
STACK_T *p_stack = NULL;
p_stack = (STACK_T *)malloc(sizeof(STACK_T));
if (NULL == p_stack) {
printf("head malloc failed!!!\r\n");
return NULL;
}
p_stack->next = NULL;
return p_stack;
}
int stack_push(STACK_T *p_head_stack, USER_DATA_T *data)
{
if (NULL == p_head_stack) {
return -1;
}
STACK_T *p_stack = (STACK_T *)malloc(sizeof(STACK_T));
if (NULL == p_stack) {
printf("head malloc failed!!!\r\n");
return -1;
}
memcpy(&p_stack->data, data, sizeof(USER_DATA_T));
p_stack->next = p_head_stack->next;
p_head_stack->next = p_stack;
return 0;
}
int stack_pop(STACK_T *p_head_stack, USER_DATA_T *data)
{
if (NULL == p_head_stack) {
return -1;
}
STACK_T *p_stack = p_head_stack->next;
if (NULL == p_stack) {
printf("stack is empty\r\n");
return -1;
}
memcpy(data, &p_stack->data, sizeof(USER_DATA_T));
p_head_stack->next = p_stack->next;
free(p_stack);
p_stack = NULL;
return 0;
}
int main(void)
{
int i = 0;
USER_DATA_T data;
USER_DATA_T read_data;
head_stack = stack_init();
if (NULL == head_stack) {
printf("stack init failed!\r\n");
}
data.id = 1;
i = stack_push(head_stack, &data);
if (-1 == i) {
printf("stack push failed\r\n");
}
data.id = 2;
i = stack_push(head_stack, &data);
if (-1 == i) {
printf("stack push failed\r\n");
}
data.id = 3;
i = stack_push(head_stack, &data);
if (-1 == i) {
printf("stack push failed\r\n");
}
i = stack_pop(head_stack, &read_data);
if (-1 == i) {
printf("stack pop failed\r\n");
} else {
printf("read_data.id:%d\r\n", read_data);
}
i = stack_pop(head_stack, &read_data);
if (-1 == i) {
printf("stack pop failed\r\n");
} else {
printf("read_data.id:%d\r\n", read_data);
}
i = stack_pop(head_stack, &read_data);
if (-1 == i) {
printf("stack pop failed\r\n");
} else {
printf("read_data.id:%d\r\n", read_data);
}
i = stack_pop(head_stack, &read_data);
if (-1 == i) {
printf("stack pop failed\r\n");
} else {
printf("read_data.id:%d\r\n", read_data);
}
return 0;
}
运行结果:
2.1. 栈的初始化
head_stack = stack_init();
if (NULL == head_stack) {
printf("stack init failed!\r\n");
}
2.2. 入栈
data.id = 1;
i = stack_push(head_stack, &data);
if (-1 == i) {
printf("stack push failed\r\n");
}
2.3. 出栈
i = stack_pop(head_stack, &read_data);
if (-1 == i) {
printf("stack pop failed\r\n");
} else {
printf("read_data.id:%d\r\n", read_data);
}