第十三章 数据结构基础--栈

本文介绍了一种使用链表实现栈数据结构的方法,并提供了具体的C语言代码示例,包括入栈、出栈操作及主函数调用流程。此外,还展示了参数传递时的压栈顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.1 入栈

入栈:
#include <stdlib.h>

typedef struct student {
int age;
struct student *next;
}Stu;

typedef struct stackqueue {
Stu *base, *top;
}stack;

stack *PushStack(stack *head, int age) {
Stu *cur_stu = NULL;
cur_stu = (Stu *)malloc(sizeof(Stu));
cur_stu->age =  age;
cur_stu->next = NULL;

if (head->base == NULL) {
head->base = cur_stu;
head->top = cur_stu;
} else {
head->top->next = cur_stu;
head->top = cur_stu;
}
return head;
}

1.2 出栈

stack *PopStack(stack *head) {
Stu *cur_stu = NULL;

if (head->base == NULL) {
printf("had removed.\n");
} else {
cur_stu = head->base;
if (head->base == head->top) {
head->base = NULL;
head->top = NULL;
} else {
while (cur_stu->next != head->top) {
cur_stu = cur_stu->next;
}
head->top = cur_stu;
free(head->top->next);
head->top->next = NULL;
}
}
return head;
}

1.3 main函数调用

int main() {
stack *head = NULL;
int age[5] = {1,2,3,4,5};

head = (stack *)malloc(sizeof(stack));
head->base = NULL;
head->top = NULL;

head = PushStack(head, age[0]);
head = PushStack(head, age[1]);
head = PushStack(head, age[2]);
head = PushStack(head, age[3]);
head = PushStack(head, age[4]);

head = PopStack(head);

return 0;
}


注:此处的栈,与内存空间中的栈不同:此处是由链表组成的栈空间。

1.4 栈的参数压栈顺序

void func(int i, char *p) {
int *q = &i;
char *Q = p;
printf("&i: %p, &p: %p", &i, &p);
return;
}

int main() {
int i = 0x22222222;
char szTest[] = "aaaa";
func(i, szTest);
return 0 ;
}


运行结果如下图所示:函数的地址在栈空间的地址是0x003ef898。先压szTest的地址,再压i的地址,最后压函数的地址。


Windows的栈空间如图所示:栈空间由高地址向低地址生长;一般系统的栈顶地址与栈的容量是系统预
先规定好的,所以每个函数的栈的栈顶地址不能小于系统的栈顶地址。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值