栈2: 栈的链式存储
栈的结点
//链式栈的结点
typedef struct LINKNODE{
struct LINKNODE *next;
} LinkNode;
链式栈的结构
//链式栈
typedef struct LINKSTACK{
LinkNode head;
int size;
} LinkStack;
栈的初始化
LinkStack* Init_LinkStack(){
LinkStack *stack = (LinkStack*)malloc(sizeof(LinkStack));
stack->head.next = NULL;
stack->size=0;
//返回栈顶
return stack;
};
入栈(头插法)
//栈是先进后出, 头插法更加适合
void Push_LinkStack(LinkStack* stack, LinkNode *data){
if(stack==NULL) return;
if(data==NULL) return;
data->next = stack->head.next;
stack->head.next = data;
stack->size++;
};
返回栈顶元素
LinkNode* Top_LinkStack(LinkStack* stack){
if(stack==NULL) return NULL;
if(stack->size==0) return NULL;
return stack->head.next;
};
出栈(删除第一个元素)
void Pop_LinkStack(LinkStack* stack){
if(stack==NULL) return;
if(stack->size==0) return;
LinkNode *curNode = stack->head.next;
stack->head.next = stack->head.next->next;
curNode->next = NULL;
free(curNode);
stack->size--;
};
返回栈元素个数
int Size_LinkStack(LinkStack* stack){
if(stack==NULL) return -1;
return stack->size;
};
清空
void Clear_LinkStack(LinkStack* stack){
if(stack==NULL) return;
stack->head.next = NULL;
stack->size = 0;
};
销毁
void FreeSpace_LinkStack(LinkStack* stack){
if(stack==NULL) return;
free(stack);
};
测试
自定义栈结构
typedef struct PERSON{
LinkNode node;
char name[64];
int age;
} Person;
测试
int main(){
//初始化栈
LinkStack *stack = Init_LinkStack();
//创建数据
Person p1,p2,p3;
//strcpy(char *dest, const char *src) 把 src 所指向的字符串复制到 dest。
strcpy(p1.name, "aaa");
strcpy(p2.name, "bbb");
strcpy(p3.name, "ccc");
p1.age = 10;
p2.age = 20;
p3.age = 30;
//入栈
Push_LinkStack(stack, (LinkNode*)&p1); //进行类型的强制转换
Push_LinkStack(stack, (LinkNode*)&p2);
Push_LinkStack(stack, (LinkNode*)&p3);
//输出
while(Size_LinkStack(stack)>0){
//取出栈顶元素
Person *p = (Person*)Top_LinkStack(stack);
cout << p->name << " " << p->age << endl;
//弹出栈顶元素
Pop_LinkStack(stack);
}
//销毁栈
FreeSpace_LinkStack(stack);
system("pause");
return 0;
}
标签:LinkStack,存储,return,head,next,链式,NULL,stack
From: https://www.cnblogs.com/HIK4RU44/p/18144290