基本知识
```c
顺序栈
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int data[20];
int top;
}stqstack;
void PUSH(stqstack *s,int x)//指针双向传递:指针的所指的内容双向传递 s->top是指针所指的内容,可双向传递,不用return
{
s->top++;s->data[s->top]=x;
}
/*stqstack *PUSH(stqstack *s,int x)//返回的是指针函数也是指针类型的
{
s->top++;s->data[s->``top]=x;
return s;
}若要return s函数必须是指针型,否则直接空型不return,因为指针双向传递,所以值会改变*/
void SETNULL(stqstack *s)
{
s->top=-1;
}
int POP(stqstack *s)//
{
if(s->top==-1) {
printf("nn");return NULL;}//返回NULL不会返回任何值,因为写了int,所以必须return NULL,或者直接return
else
{
s->top--;
return (s->data[s->top+1]);
}
}
int main()
{
stqstack *s;
s=malloc(sizeof(stqstack));//分配地址不能少
s->top=-1;//要先置空
PUSH(s,1);//不用再用s=了,因为指针,双向传递
int x=POP(s);
printf("%d",x);
SETNULL(s);
POP(s);
return 0;
}
输出 1nn
链栈
#include <stdio.h>
#include <stdlib.h>
typedef struct node1
{
int data;
struct node1 *next ;
}stack;
stack *POP(stack *q,int *m)//取//链栈,与顺序栈不同,q=q->next 改变了指针变量的地址,所以不会双向传递,需要return
{
*m=q->data;
q=q->next;
return q;
}
stack *PUSH(stack *q,int x)//入
{
stack *s;
s= malloc(sizeof(stack));
s->data=x;
s->next=q;
q=s;
return q;
}
int main()
{
stack *top;
top=NULL;
top=PUSH(top,1);
top=PUSH(top,2);
int *m;
m=malloc(sizeof(int));
top=POP(top,m);//单向传递,所以需要top=
top=POP(top,m);
printf("%d",*m);
return 0;
}
//第二种方法,传递指针的地址,双向传递
//想要实现值的双向传递,必须保证自定义函数对形参的操作是通过指向形参地址以后再取值而进行的操作,此时如果仅仅把要修改的实参作为形参传过去,那么自定义函数的修改无效,像此题你如果想只用void类型的函数改top指针,就必须把top的地址传过去,因此就有了指针的指针,否则的话就要返回自定义函数里已经处理好的指针以此来更新原来的top
#include <stdio.h>
#include <stdlib.h>
typedef struct node1
{
int data;
struct node1* next;