Chained stack creation data structure C language version

Abstract: The chained stack is first of all chained, and malloc needs to be used to open up space in the heap area, so it saves space compared to the sequential stack. Secondly, the stack is characterized by first-in-last-out (FILO), which is similar to the queue is the opposite operation. Just like loading a bullet, the bullet that goes in first always comes out last.

Implementation function: linkstack.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include "linkstack.h"
Linkstack *Create_Link()  //创建头节点
{
	Linkstack *head =(Linkstack *)malloc(sizeof(Linkstack));
	if(NULL == head){
		printf("head is NULL\n");
		return NULL;
	}
	head->next=NULL;
	head->data=-1;
	return head;
}
int Linkstack_Is_Empty(Linkstack *head)//判空
{
	if(head->next == NULL){
		return 0;
	}
	return 1;
}
int Linkstack_Lenth(Linkstack *head)//计算表长
{	
	Linkstack *p;
	int i=0;
	p=head->next;
	while(p!= NULL){
		i++;
		p=p->next;
		
	}
	return i;
}	
void Linkstack_posh(Linkstack *head,data_t data)//入栈
{
	Linkstack *new =(Linkstack *)malloc(sizeof(Linkstack));
	if(NULL == new){
		printf("new is NULL\n");
		return;
	}
	new->data=data;
	new->next=NULL;
	new->next=head->next;
	head->next=new;
}
void Linkstack_pop(Linkstack *head,data_t *data){//出栈
	if(Linkstack_Is_Empty(head)==0){
		printf("stack is null\n");
		return;
	}
	Linkstack *p=head->next;
	head->next=p->next;
	*data=p->data;
	free(p);
	p=NULL;
}

Header file (function declaration): linkstack.h

#ifndef _LINKSTACK_H
#define _LINKSTACK_H
typedef int data_t;
typedef struct linkstack{
    data_t data;
    struct linkstack *next;
}Linkstack;
Linkstack *Create_Link();

void Linkstack_posh(Linkstack *head,data_t data);//从表头插入数据

int Linkstack_Lenth(Linkstack *head);//计算表长

void Linkstack_pop(Linkstack *head,data_t *data);//pop

int Linkstack_Is_Empty(Linkstack *head);//判空

#endif

Main function: main.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include "linkstack.h"
int main(){
Linkstack *head=Create_Link();
int n=10;
while(n--){
Linkstack_posh(head,n);//从表头插入数据
}

int data=0;
while(head->next!=NULL){
Linkstack_pop(head,&data);
	printf("%d ",data);
}
puts(" ");
	return 0;
}

good! This is the end of today's sharing. If there is something wrong, please correct me a lot, and don't hesitate to enlighten me, thank you! (Just because you are so beautiful)

Guess you like

Origin blog.csdn.net/weixin_56187542/article/details/126129772