C语言用链表实现栈(链表实现)

首先知道栈的特性是先进后出,类似于把数据放在一个单向开口的管道当中,先放的只能最后拿出来。

当然也可以先入栈A,在出栈A这样的操作,顺序表和链表都可以实现栈的操作,整理用链表实现;

先看main.c文件

#include "listshed.h"

int main()
{
	Listshed* L= Listshed_Creat();//初始化
	for (int i = 0; i < 10; i++)
	{
		Listshed_Inser(L,i);//头插入栈
	}
	Listshed_Show(L);
	for (int i = 0; i < 10; i++)
	{
		printf("%2d",Listshed_Pull(L));//头插入栈
	}
	puts(" ");
	Listshed_Empty(L);//清空
	Listshed_Destroy(&L);//销毁
	return 0;
}

需要注意的是头插入栈的操作,我是123456789的顺序入栈,出栈顺序是987654321,在插入数据时输入或者叫栈里面存放数据的顺序应该时9,8,7,6,5,4,3,2,1.

1先入栈,所以1是栈底,9最后入栈,所以是栈顶,再看listshed.c文件,实现具体的功能:

#include "listshed.h"

Listshed* Listshed_Creat()
{
	Node* N = (Node*)malloc(sizeof(Node));
	if (N==NULL)
	{
		printf("node malloc,failsd!\n");
		return NULL;
	}
	N->next = NULL;
	Listshed* L = (Listshed*)malloc(sizeof(Listshed));
	if (L == NULL)
	{
		printf("Listshed malloc,failsd!\n");
		return NULL;
	}
	L->top = N;
	return L;
}
void Listshed_Inser(Listshed* L,data_t data)//头插入栈
{
	Node* q = (Node*)malloc(sizeof(Node));
	if (q == NULL)
	{
		printf("q malloc,failsd!\n");
		return ;
	}
	q->data = data;
	q->next = L->top->next;
	L->top->next = q;
}
data_t Listshed_Pull(Listshed* L)//出栈
{
	if (L->top->next==NULL)
	{
		printf("栈空!\n");
		return NULL;
	}
	Node* q = L->top->next;
	data_t data = q->data;
	L->top->next = q->next;
	free(q);
	q = NULL;
	return data;
}
void Listshed_Empty(Listshed* L)//清空
{
	while (L->top->next != NULL)
	{
		Node* q = L->top->next;
		data_t data = q->data;
		L->top->next = q->next;
		free(q);
		q = NULL;
	}
	printf("栈空!\n");
	return;
}
void Listshed_Destroy(Listshed** L)//销毁使用前先调用清空函数
{
	free(*L);
	*L = NULL;
	printf("栈已销毁!\n");
	return ;
}
void Listshed_Show(Listshed* L)//打印
{
	Node* q = L->top->next;
	while (q->next!= NULL)
	{
		
		printf("%2d", q->data);
		q = q->next;
	}
	if (q->next == NULL)
	{
		printf("%2d", q->data);
	}
	puts(" ");
	return;
}

需要注意的是结点的创建于销毁,free(*X);x=null;就可以了

再看listshed.h文件,

#ifndef __LISTSHED_H__
#define __LISTSHED_H__
typedef int data_t;
typedef struct node
{
	data_t data;
	struct node* next;
}Node;
typedef struct listshed
{
	struct node* top;
}Listshed;
#include <stdio.h>
#include <stdlib.h>
Listshed* Listshed_Creat();//初始化
void Listshed_Inser(Listshed* L,data_t data);//头插入栈
data_t Listshed_Pull(Listshed* L);//出栈
void Listshed_Empty(Listshed* L);//清空
void Listshed_Destroy(Listshed** L);//销毁
void Listshed_Show(Listshed* L);//打印
#endif 

.h文件的函数声明后面都注释有具体的函数功能,看不懂listshed.c的可以结合.h文件来看,就非常好理解了。

接下来是运行结果:

第一行是入栈后存放数据的顺序,10个元素,从0开始存放,所以看起来和第二行输出的元素一样,如果不喜欢这组数据,或有其他要求,可以将main 函数的这一行

替换成:


int N;
for(int i=0;i<10;i++)
{
    scanf("%d",&N);
    Listshed_Inser(L,N);
}

链表的实现就这些,如还需要什么具体的功能再在此基础上进行修改或添加。 

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值