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