//链式栈
typedef struct LinkStack//创建结构体
{
int data;
struct LinkStack* lp;
}LS;
LS* Creat()//创建栈
{
LS* head = (LS*)malloc(sizeof(LS));
head->lp == NULL;
return head;
}
LS* push(LS* head, int x)//压栈
{
LS* node = (LS*)malloc(sizeof(LS));
node->data = x;
node->lp = head;
head = node;
printf("入栈成功!\n");
return head;
}
LS* Out(LS *head,int *x)//出栈
{
LS* tmp = head;
if (head->lp == NULL)
{
printf("栈为空!\n");
return 0;
}
else
{
*x = head->data;
head = head->lp;
free(tmp);
return head;
}
}
int main()
{
LS* head = Creat();
int val,n;
printf("请输入想要录入的个数:\n");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("请输入需要录入的整数:\n");
scanf("%d", &val);
head = push(head, val);
}
for (int i = 0; i < n; i++)
{
int put;
head=Out(head,&put);
printf("元素出栈:%d ",put);
}
return 0;
}
顺序栈:
//顺序栈
#define MAX 100
typedef int DATA;
typedef struct stack {
DATA data[MAX];
int top;
}Stack;
Stack* Creat()
{
Stack* phead = (Stack*)malloc(sizeof(Stack));
phead->top = -1;
return phead;
}
void Push(Stack *phead,int x)
{
if (phead->top == MAX - 1)
{
printf("栈满!\n");
return;
}
else
{
phead->top++;
phead->data[phead->top]=x;
printf("入栈成功!\n");
}
}
int Out(Stack* phead)
{
int x=0;
if (phead->top == -1)
{
printf("栈为空!\n");
return 0;
}
else
{
x = phead->data[phead->top];
phead->top--;
return x;
}
}
int main()
{
int n;
Stack* phead = Creat();
int val;
printf("请输入想要录入的个数:\n");
scanf("%d", &n);
for(int i=0;i<n;i++)
{
printf("请输入需要录入的整数:\n");
scanf("%d", &val);
Push(phead, val);
}
for (int i = 0; i < n; i++)
{
int put = Out(phead);
printf("%d ", put);
}
return 0;
}