单链表的初始化,头插法,尾插法,按值查找与按位查找,链表的长度与链表的遍历

#include <stdio.h>
#include <stdlib.h>
typedef struct LNode {
	int data;
	struct LNode* next;
}LNode,*LinkList;
//初始化(无头节点)
bool InitList_NH(LinkList& L) {
	L = NULL;
	return true;
}
//初始化(有头节点)
bool InitList_H(LinkList& L) {
	L = (LNode*)malloc(sizeof(LNode));
	if (L == NULL)
		return false;
	L->next = NULL;
	return true;
}
//按位查找
LNode* GetElem(LinkList L, int i) {
	if (i < 1) {
		return NULL;
	}
	int j = 0;
	LNode* p = L;
	while (p != NULL && j < i ) {
		p = p->next;
		j++;
	}
	return p;
}
//按值查找
LNode* LocateElem(LinkList L, int e) {
	LNode* p = L->next;
	if (p == NULL) {
		return NULL;
	}
	while (p != NULL && p->data != e) {
		p = p->next;
	}
	return p;
}
int length(LinkList L) {
	int len = 0;
	if (L == NULL)
		return 0;
	LNode* p = L->next;
	while (p != NULL) {
		p = p->next;
		len++;
	}
	return len;
}
LinkList ListTailInsert(LinkList& L) {
	LNode* p, * t = L;
	for (int i = 0; i < 5; i++) {
		p = (LNode*)malloc(sizeof(LNode));
		p->data = i;
		t->next=p;
		t = p;
	}
	p->next = NULL;
	return L;
}
LinkList ListHeadInsert(LinkList L) {
	LNode* p, * h = L;
	for (int i = 0; i < 5; i++) {
		p = (LNode*)malloc(sizeof(LNode));
		p->data = i;
		p->next = h->next;
		h->next = p;
	}
	return L;
}
//链表的遍历
void print(LinkList L) {
	LNode* p = L->next;
	while (p != NULL) {
		printf("The content is %d\n", p->data);
		p = p->next;
	}
}
int main() {
	LinkList L1,L2;
	if (InitList_H(L1)) {
		printf("The List was initialized successfully\n");
	}
	else {
		printf("List initialization failed\n");
	}
	if (InitList_H(L2)) {
		printf("The List was initialized successfully\n");
	}
	else {
		printf("List initialization failed\n");
	}
	ListTailInsert(L1);
	printf("This is Tail Insert\n");
	print(L1);
	ListHeadInsert(L2);
	printf("This is Head Insert\n");
	print(L2);
	int x;
	printf("Enter the order you want to find\n");
	scanf_s("%d", &x);
	printf("The result is %d\n", GetElem(L1, x)->data);
	printf("Enter the number you want to find\n");
	scanf_s("%d", &x);
	printf("The result is %d\n", LocateElem(L1, x)->data);
	
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值