在计算机中有一个重要的概念——堆栈。堆栈是指这样一段内存,?它可以理解为一个?筒结构,?先放进筒中的数据被后放进筒中的数据“压住”,只有在后放进筒中的数据都取出后,?先放进去的数据才能被取出,这称为“后进先出”。堆栈的长度可以随意增加。堆栈结构可以?用链表实现。
#include <stdio.h>
#include <stdlib.h>
typedef struct stack stack;
struct stack{
int data;
stack *next;
};
stack *head,*pr;
//压入
void PushStack(int data)
{
stack *p = (stack *)malloc(sizeof(stack));
stack *q;
if(head->next==NULL)
{
p->data = data;
p->next = NULL;
head->next = p;
}
else
{
q = head->next;
p->next = q;
p->data = data;
head->next = p;
}
}
//弹出
void PopStack()
{
stack *p;
if(head->next->next==NULL)
{
printf("no data\n");
}
else
{
p = head->next;
head->next = p->next;
}
free(p);
}
//打印
void PrintStack()
{
stack *p;
p = head->next;
printf("从栈顶向下遍历为:\n");
while(p)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main() {
int data,pushNum,popNum,i;
char ch;
head = (stack *)malloc(sizeof(stack));
head->next = NULL;
printf("请输入要压入堆栈的数的个数:");
scanf("%d",&pushNum);
printf("请输入数据:\n");
for(i = 0;i < pushNum;i++)
{
scanf("%d",&data);
PushStack(data);
}
PrintStack();
flag:;
printf("你是否要将数据弹出堆栈?(y/n)");
getchar();
scanf("%c",&ch);
if(ch == 'n')
{
PrintStack();
}
else if(ch == 'y')
{
printf("你想弹出多少数据?");
scanf("%d",&popNum);
while(popNum > pushNum)
{
printf("错误的数量!\n");
printf("你想弹出多少数据?");
scanf("%d",&popNum);
}
while(popNum--)
{
PopStack();
}
PrintStack();
}
else
{
printf("错误的指令!\n");
goto flag;
}
return 0;
}
另一个:
#include<stdio.h>
#include<stdlib.h>
struct stack
{
int data;
struct stack *next;
};
typedef struct stack stack;
stack *head,*pr;
int nodeNumber = 0;
stack *CreateNode(int data)
{
stack *p;
p = (stack *)malloc(sizeof(stack));
if(p == NULL)
{
printf("No enough memory!\n");
exit(0);
}
p->next = NULL;
p->data = data;
return p;
}
stack *Pushstack(int num)
{
if(nodeNumber == 0)
{
head = CreateNode(num);
pr = head;
nodeNumber++;
}
else
{
pr->next = CreateNode(num);
pr = pr->next;
nodeNumber++;
}
return pr;
}
int Popstack(void)
{
stack *p;
int result;
p = head;
while(1)
{
if(p->next == NULL)
{
break;
}
else
{
pr = p;
p = p->next;
nodeNumber--;
}
}
pr->next = NULL;
result = p->data;
free(p);
return result;
}
int main()
{
int pushNum;
int popNum[5];
int i,n;
printf("How many Data do you want push?");
scanf("%d",&n);
for(i = 0;i < n;i++)
{
scanf("%d",&pushNum);
Pushstack(pushNum);
printf("Push %dth Data : %d\n",i+1,pushNum);
}
for(i = 0;i < n;i++)
{
popNum[i] = Popstack();
printf("Pop %dth Data : %d\n",n-i,popNum[i]);
}
return 0;
}
|