数据结构之单链表基本功能实现

本文详细介绍了如何使用C语言实现单链表的基本功能,包括创建链表、插入节点、删除节点和打印链表等操作。通过实例代码解析,帮助读者理解单链表的数据结构及其操作方法。
摘要由CSDN通过智能技术生成

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

typedef struct LNode {
	int data;
	struct LNode* next;
}LNode, * LinkList;

//初始化单链表
bool initList(LinkList& L)
{
	L = (LinkList)malloc(sizeof(LNode));
	//static_assert(L!=NULL);
	L->next = NULL;
	return true;
}

//头插法  LNode*(强调结点)=LinkList(强调单链表的指针)
LNode* creatList(LinkList& L)
{
	LNode* S;

	int x;
	scanf("%d", &x);

	while (x != 0)
	{
		S = (LNode*)malloc(sizeof(LNode));
		S->data = x;
		S->next = L->next;
		L->next = S;
		scanf("%d", &x);
	}
	return L;
}

//尾插法
LNode* tailPlugList(LinkList& L)
{
	LinkList s, r = L;
	int x;
	scanf("%d", &x);

	while (x != 0)
	{
		s = (LNode*)malloc(sizeof(LNode));
		s->data = x;
		if (L->next == NULL)
		{
			s->next = r->next;
			r->next = s;
			r = s;
		}
		r->next = s;
		r = s;
		scanf("%d", &x);
	}
	r->next = NULL;
	return L;
}

//按索引查找
LNode* LocateList(LinkList L, int i)
{
	LNode* p;
	p = L->next;
	int j = 1;

	if (i == 0)
	{
		return L;
	}
	if (i < 1)
	{
		return NULL;
	}
	while (p && j < i)
	{
		p = p->next;
		j++;
	}

	return p;
}

//按值查找
LNode* getElemList(LinkList L, int x)
{
	LNode* p = L->next;

	while (p && p->data != x)
	{
		p = p->next;
	}

	return p;
}

//按索引将值插入链表
bool insertList(LinkList& L, int i, int x)
{
	LinkList temp = LocateList(L, i - 1);
	if (NULL == temp)  return false;
	if (i < 1) return false;

	LinkList s = (LNode*)malloc(sizeof(LNode));
	s->data = x;
	s->next = temp->next;
	temp->next = s;
	return true;
}

//按值删除链表
bool deleteList(LinkList& L, int i)
{
	LinkList temp = L;
	if (L)
	{
		temp = LocateList(L, i - 1);
	}
	LinkList s = temp->next;

	if (s)
	{
		temp->next = s->next;
	}

	free(s);

	return true;

}

//输出链表
void printList(LinkList L)
{
	L = L->next;
	while (L != NULL)
	{
		printf("%d ", L->data);
		L = L->next;
	}
}


//int main()
//{
//	LinkList L;
//	LinkList T;
//
//	initList(L);
//	//creatList(L);
//	tailPlugList(L);
//	printList(L);
//
//	T = LocateList(L, 2);
//	if (T)
//	{
//		printf("\n第2个位置的值=%d", T->data);
//	}
//
//	T = getElemList(L, 5);
//	if (T)
//	{
//		printf("\n5存在=%d", T->data);
//	}
//	deleteList(L, 2);
//	printf("\n删除第二个元素后的链表:\n");
//
//	printList(L);
//
//	insertList(L, 2, 6);
//	printf("\n在第二个位置插入6后的链表:\n");
//	printList(L);
//
//	return 0;
//}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风&似恋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值