29.单链表的C语言完整实现

主要包含:

单链表的数据结构,初始化,打印输出,建立单链表(尾插法),元素按位插入,按位删除,按值查找。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAXSIZE 100
#define ElemType int
#define Status int

//单链表的数据结构
typedef struct LNode
{
	ElemType data;
	struct LNode *next;
}LNode, *LinkList;

//初始化
int InitList(LinkList &L)
{
	L = (LNode *)malloc(sizeof(LNode));
	L->next = NULL;
	return 1;
}

//输出
void PrintList(LinkList L)
{
	printf("当前单链表的所有元素:");
	LNode *p;
	p = L->next;
	while (p != NULL)
	{
		printf("[%d] ", p->data);
		p = p->next;
	}
	printf("\n");
}

//尾插法创建单链表
int Create(LinkList &L)
{
	int n, e;
	LNode *temp = L;//声明一个指针指向头结点,用于遍历链表   

	printf("请输入要输入元素的个数:");
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{

		LNode *a = (LNode*)malloc(sizeof(LNode));
		printf("请输入第%d元素的值:", (i));
		scanf("%d", &e);
		a->data = e;
		temp->next = a;
		a->next = NULL;
		temp = temp->next;
	}
	return 1;
}

//插入元素
int InsertList(LNode *L, int i, ElemType e)
{
	LNode *p = L;
	int j = 0;
	while (p && (j < i - 1))  //寻找要插入位置的前驱结点,让p指向它
	{
		p = p->next;
		++j;
	}
	if (!p || j > i - 1) return 0;	//插入位置非法,返回0
	LNode *s = (LNode *)malloc(sizeof(LNode));
	s->data = e;  //创建一个新结点存放要插入的元素e
	s->next = p->next;  //把新结点的指针域指向p->next
	p->next = s;  //把p->next指向要插入的新结点
	return 1;
}

//删除元素
int DeleteList(LNode *L, int i)
{
	LNode *p = L;
	int j = 0;
	while (p->next && (j < i - 1))	//寻找要删除结点的前驱结点,让p指向它
	{
		p = p->next;
		++j;
	}
	if (!p->next || j > i - 1) return 0;  //删除位置非法,返回0
	LNode *q;
	q = p->next;  //暂存删除结点,以便随后释放
	p->next = q->next;	//把p->next指向p->next->next,即q->next
	free(q);  //释放结点
	return 1;
}

//按值查找元素
int LocateElem(LNode *L, ElemType e)
{
	int i = 1;
	LNode *p = L->next;
	while (p&&p->data != e)		//从第一个结点开始,依次向后遍历比较
	{
		p = p->next;
		i++;
	}
	if(p)	return i;
	else	return 0;	
}

int main(){
	LinkList L;
	InitList(L);
	Create(L);
	PrintList(L);
	InsertList(L, 4, 5);
	PrintList(L);
	DeleteList(L, 3);
	PrintList(L);
	printf("%d\n",LocateElem(L, 2));
	return 0;
}

输出:

请输入要输入元素的个数:5
请输入第1元素的值:1
请输入第2元素的值:2
请输入第3元素的值:3
请输入第4元素的值:4
请输入第5元素的值:5
当前单链表的所有元素:[1] [2] [3] [4] [5]
当前单链表的所有元素:[1] [2] [3] [5] [4] [5]
当前单链表的所有元素:[1] [2] [5] [4] [5]
2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

北京地铁1号线

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

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

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

打赏作者

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

抵扣说明:

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

余额充值