#include<stdio.h>
#include<stdlib.h>
typedef int DataType;
typedef struct node
{
DataType data;
struct node *next;
} Node;
void InitStack(Node *top)
{
top = (Node *)malloc(sizeof(Node));
top->next = NULL;
}
int Push(Node *top, DataType x)
{
Node * p;
p = (Node *)malloc(sizeof(Node));
p->data = x;
p->next = top->next;
top->next = p;
return 1;
}
int Pop(Node *top, DataType *x)
{
Node *p;
p = top->next;
if (p == NULL) return 0;
top->next = p->next;
*x = p->data;
free(p);
return 1;
}
int GetTop(Node *top, DataType *p)
{
if(top->next == NULL) return 0;
*p = top->next->data;
return 1;
}
int main() {
Node top;
InitStack(&top);
DataType x;
printf("How many data to push?\n");
scanf("%d",&x);
int i = x;
while(i--){scanf("%d",&x);Push(&top, x);}
if (GetTop(&top,&x) == 0) printf("Failed to get top data\n");
else printf("Top data: %d\n",x);
if(Pop(&top, &x) == 0) printf("Failed to pop\n");
else printf("Pop data: %d\n", x);
if (GetTop(&top,&x) == 0) printf("Failed to get top data\n");
else printf("Top data: %d\n",x);
return 0;
}
运行结果:
How many data to push?
5
1 2 3 4 5
Top data: 5
Pop data: 5
Top data: 4