链表基本功能:初始化、增、删、查、改

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

typedef struct Node {
	int val;
	struct Node* next;
}M;

M* listCreat();//初始化
void listOut();//打印
M* listAdd();//增
M* listDel(); //删
void listSear();//查
M* listAdj();//改 

int main() {
	printf("%s\n", "链表长度:");
	int Len;
	scanf_s("%d",&Len);
	M* List = listCreat(Len);
	printf("\n%s\n", "打印List:");
	listOut(List);
	
	printf("\n%s\n", "插入位置:");
	int Index;
	scanf_s("%d", &Index);
	List=listAdd(List,Index);
	printf("\n%s\n", "打印List:");
	listOut(List);

	printf("\n%s\n", "删除位置:");
	int Del;
	scanf_s("%d", &Del);
	List=listDel(List,Del);
	printf("\n%s\n", "打印List:");
	listOut(List);

	printf("\n%s\n", "查找位置:");
	int Search;
	scanf_s("%d", &Search);
	listSear(List,Search);
	printf("\n%s\n", "打印List:");
	listOut(List);
	
	printf("\n%s\n", "更改位置:");
	int Adjust,val;
	scanf_s("%d", &Adjust);
	printf("\n%s\n", "val:");
	scanf_s("%d", &val);

	List = listAdj(List, Adjust, val);
	printf("\n%s\n", "打印List:");
	listOut(List);

	return 0;
}

M* listCreat(int step) {//初始化
	M* head = NULL, * last = NULL, * p = NULL;
	int steps = 0;
	do {
		M* p = (M*)malloc(sizeof(M));//申请储存空间
		p->next = NULL;

		printf("输入val:");
		scanf_s("%d", &(p->val));

		if (!head) {
			head = p;
		}
		else {
			last->next = p;
		}
		last = p;//令 last 指向 head 末尾
		steps++;
	} while (steps < step);
	return head;
}

void listOut(M* head) {//输出链表
	while (head != NULL) {
		printf("val:%d\n", head->val);
		head = head->next;
	}
}

M* listAdd(M* head, int Index) {
	M* p = (M*)malloc(sizeof(M));//申请储存空间
	p->next = NULL;
	printf("输入val:");
	scanf_s("%d", &(p->val));
	if (Index == 0) {
		p->next = head;
		head = p;
	}
	else {
		M* In = head;
		while (Index - 1 > 0) {
			Index--;
			In = In->next;
		}
		p->next = In->next;
		In->next = p;
	}
	return head;
}

M* listDel(M* head, int Index) {
	if (Index == 0) {
		head = head->next;
	}
	else {
		M* In = head;
		while (Index - 1 > 0) {
			Index--;
			In = In->next;
		}
		In->next = In->next->next;
	}
	return head;
}

void listSear(M* head, int Index) {
	M* p = head;
	while (Index > 0) {
		Index--;
		p = p->next;
	}
	printf("val:%d\n", p->val);
}

M* listAdj(M* head, int Index, int data) {
	M* p = head;
	while (Index > 0) {
		Index--;
		p = p->next;
	}
	p->val = data;
	return head;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值