栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言实现单链表

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言实现单链表


#include
#include

typedef struct Node
{
	int data;     //数据域
	struct Node* next; //指针域
}Node;

//创建链表(表头)
Node* Create()
{
	Node* L = (Node*)malloc(sizeof(Node));
		L->next = NULL; //初始化为NULL
		L->data = 0;
		return L;
}


void HeadInser(Node* L, int data)
{
	Node* Y = (Node*)malloc(sizeof(Node));
		Y->data = data;
		Y->next = L->next;//新的节点指向头结点指向的那一个节点
		L->next = Y;  //头结点指向新的节点
}




void TailInser(Node* L, int data)
{
	Node* Y = (Node*)malloc(sizeof(Node));
		//无论是否为空 都要实现的部分放外面可减少代码量
		Y->data = data;
		//如果L为空
		if (!L)
		{
			Y->next = L->next;//新节点Y指向头结点指向的下一个
			L->next = Y;//头结点指向Y
		}
		else 
		{
			while (L->next)//如果不为空的时候找到最后一个节点
			{
				L = L->next;
			}
			Y->next = L->next;
			L->next = Y;
		}
}

void PrintList(Node* L)
{
	Node* Y = L;
	Y = Y->next;//不打印表头
	while (Y)
	{
		printf("%d -> ", Y->data);
		Y = Y->next;
	}
	printf("NULLn");
}


void List_Find(Node* L,int data)
{
	Node* Y = L->next;//不查找表头
	while (Y)
	{
		if (Y->data == data)
		{
			printf("找到了:%dn", Y->data);
			return;
		}
		Y = Y->next;
	}
	printf("抱歉,链表中没有查询值n");
}



void List_Delet(Node* L, int data)
{
	Node* Y = L;
	if (Y->next == NULL)//空链表
	{
		free(Y);
		Y = NULL;
		return;
	}
	else
	{
		while (Y->next)
		{
			if (Y->next->data == data)
			{
				Node* P = Y->next;//记住删除的位置
				Y->next = Y->next->next;//指向下下个结点
				printf("删除值为%d后的链表: ",P->data);
				free(P);
				P = NULL;
				return;
			}
			Y = Y->next;
		}
	}
	printf("没有找到需要删除的结点n");
}

void List_Destroy(Node* L)
{
	Node* Y = L;
	while (L)
	{
		L = L->next;
		free(Y);
		Y = NULL;
		Y = L;
	}
	if (L == NULL)
	{
		printf("删除链表成功");
	}
}
int main(void)
{
	Node* LY = Create();
	HeadInser(LY, 1);
	HeadInser(LY, 2);
	HeadInser(LY, 3);
	TailInser(LY, 4);
	TailInser(LY, 5);
	TailInser(LY, 6);
	PrintList(LY);
	List_Find(LY, 0);
	List_Delet(LY, 6);
	PrintList(LY);
	List_Destroy(LY);
//	printf("%d", LY->next->data); 因为链表已经删除 这里会报错
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/457900.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号