連鎖スタック作成データ構造 C言語版

要約: 連鎖スタックはまず第一に連鎖されており、ヒープ領域のスペースを空けるために malloc を使用する必要があるため、シーケンシャル スタックと比較してスペースを節約できます。 (FILO) はキューと似ており、その逆の操作です。弾丸を装填するのと同じように、最初に入った弾丸は常に最後に出ます。

実装関数: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;
}

ヘッダファイル(関数宣言):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.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;
}

良い!今日の共有はこれで終わります。何か間違っている場合は、たくさん修正して、遠慮せずに教えてください。ありがとうございました。(あなたがとても美しいという理由だけで)

おすすめ

転載: blog.csdn.net/weixin_56187542/article/details/126129772