数据结构——栈之链式存储
跟链表结构一样,只是多了条限制:只能从链表头插入和删除。
源码:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
/**栈的链式存储**/
typedef struct Data{
char name[10];
int age;
};
typedef struct Stack{
Data data;
Stack *top; //指向栈顶元素
};
/**初始化空栈**/
void InitStack(Stack *S){
S->top = NULL;
}
/**判断是否为空栈**/
int StackEmpty(Stack S){
//为空返回1否则返回0
if(S.top==NULL) return 1;
else return 0;
}
/**返回栈顶元素**/
void GetTop(Stack S,Data *d){
if(StackEmpty(S)==1)
printf("It's an empty stack!");
else{
strcpy(d->name,S.top->data.name);
d->age = S.top->data.age;
}
}
/**向栈顶插入新元素 入栈**/
void PushStack(Stack *S,Data d){
Stack* p = (Stack *)malloc(sizeof(Stack));
strcpy(p->data.name,d.name);
p->data.age = d.age;
p->top = S->top;
S->top = p;
}
/**从栈顶删除元素 出栈**/
void PopStack(Stack *S,Data *d){
if(StackEmpty(*S)==1){
printf("It's an empty stack!\n");
}else{
Stack *p = S->top;
S->top = p->top;
strcpy(d->name,p->data.name);
d->age = p->data.age;
}
}
/**清空栈**/
void ClearStack(Stack *S){
if(StackEmpty(*S)==1){
printf("It's already an empty stack!\n");
}else{
S->top = NULL;
}
}
/**打印栈内信息**/
void PrintStack(Stack S){
if(StackEmpty(S)==1){
printf("It's an empty stack!\n");
}else{
printf("name----age\n");
while(S.top!=NULL){
printf("%s %d\n",S.top->data.name,S.top->data.age);
S.top = S.top->top;
}
}
}
void main(){
Data d;
char name[10];
int age;
int i=1;
Stack S;
while(i){
printf("1、初始化空栈\t2、入栈\t3、出栈\t4、栈顶元素5、清空栈6、打印信息\n");
scanf("%d",&i);
switch (i){
case 1:
InitStack(&S);
break;
case 2:
printf("Input the name: ");
scanf("%s",&d.name);
printf("Input the age: ");
scanf("%d",&d.age);
PushStack(&S,d);
break;
case 3:
PopStack(&S,&d);
printf("Deleted (%s,%d)\n",d.name,d.age);
break;
case 4:
GetTop(S,&d);
printf("Top element is (%s,%d)\n",d.name,d.age);
break;
case 5:
ClearStack(&S);
break;
case 6:
PrintStack(S);
break;
default:
break;
}
}
system("pause");
}