数据结构之单链表操作

数据结构之单链表操作

一、引入文件

#include <stdio.h>
#include <malloc.h>

二、定义结构体

在这里插入图片描述

struct ListNode {
	int val;
	struct ListNode* next;
};

三、初始化链表

在这里插入图片描述

void initList(struct ListNode* L)
{
    //带头节点
	L->next = NULL;
}

四、判断链表是否为空

bool isemptyList(struct ListNode* L)
{
	//查找首元节点是否为空
	if (L->next)return false;
	else return true;
}

五、创建链表(带头节点)

void CreateList_tail(struct ListNode* L, Elemtype* a, int n)
{
	struct ListNode* h;
	h = L;//拷贝头指针

	struct ListNode* s;
	s = L->next;
	//尾插法
	for (int i = 0; i < n; i++) {
		s = (struct ListNode*)malloc(sizeof(struct ListNode));
		//尾插入节点
		s->val = a[i];
		s->next = h->next;
		h->next = s;
		//进入下一节点
		h = s;
		s = s->next;
	}
}

六、输出链表

在这里插入图片描述

void printList(struct ListNode* L) {
	printf("输出链表: ");
	struct ListNode* p;
	p = L->next;//跳过头结点到首元位置
	while (p != NULL) {
		printf("%c ", p->val);
		p = p->next;
	}
	printf("\n");
}

七、查找元素

1.判断元素是否存在

bool isexistList(struct ListNode* L, int i)
{
	int b = 0;
	while (L) {
		L=L->next;
		b++;
		if (b == i) {
			return true;
		}
	}
    if (b < i)return false;
}

2.如果存在则输出元素

void searchList(struct ListNode* L, int i, bool a)
{
	if (a == true) {
		int b = 0;
		while (L) {
			L=L->next;
			b++;
			if (b == i) {
				printf("%c ", L->val);
			}
		}
	}
}

八、主函数验证结果

void main()
{
	Elemtype a[26] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
					  'Q','R','S','T','U','V','W','X','Y','Z' };

	struct ListNode* l1;
	l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
	initList(l1);

	if (isemptyList(l1))printf("链表为空!\n");
	else printf("链表为非空!\n");

	CreateList_tail(l1, a, 26);
	printList(l1);

	searchList(l1, 4, isexistList(l1, 4));
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

有几何

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

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

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

打赏作者

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

抵扣说明:

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

余额充值