[作业]单链表的创建、插入、删除、查找

[作业]单链表的创建、插入、删除、查找

#include "stdio.h"
#include "malloc.h"
typedef struct LNode {
	int data;
	struct LNode *next;
}LNode, *LinkList;

LNode* InitLList(int low, int up) {
	LNode *head, *s, *r;	//head,r 头,尾
	head = (LNode *)malloc(sizeof(LNode));
	r = (LNode *)malloc(sizeof(LNode));
	head->data = 9527;
	head->next = r;			//设置head结点成员
	r->data = low;
	r->next = NULL;			//设置r结点成员
	for (int i = low + 1; i <= up; i++) {
		s = (LNode *)malloc(sizeof(LNode));
		s->data = i;		//i==>s.data
		s->next = r->next;	//s.next --> r.next == NULL ,设置链表末尾指针为空
		r->next = s;		//r.next --> s 的地址
		r = s;				//s为临时变量,最后链表末尾替换为r
	}
	return head;
} //InitLList

void InsertLList(LNode* l, int pos, int num) {
	int count;
	LNode *s, *p;
	if (!l) {
		printf("链表不存在");
		return;
	}
	if (pos<1) {
		printf("插入位置不存在");
	}
	p = l->next;		//p --> 头结点
	count = 1;
	while (count<pos - 1 && p) {
		p = p->next;
		count++;
	} // p --> 插入位置之前的结点
	s = (LNode*)malloc(sizeof(LNode));
	s->data = num;		//num==>s.data
	s->next = p->next;  //s.next --> 下一个节点的地址
	p->next = s;		//p.next --> s的地址
} //InsertLList

void DelLLink_p(LNode* l, int pos) {
	int count;
	LNode *p, *q;		//p为删除位置之前的结点,q为要删除位置的结点
	if (!l) {
		printf("链表不存在");
	}
	if (pos<1) {
		printf("删除位置不存在");
	}
	p = l->next;		//p --> 头结点
	count = 1;
	while (count<pos - 1 && p) {
		p = p->next;
		count++;
	} // p --> 删除位置之前的结点
	if (p->next != NULL) {
		q = p->next;		//设置临时变量q为p的下一个结点 即 要删除的结点 
		p->next = q->next;	//p.next --> q.next 即 p结点指向q的下一个结点
		free(q);            //释放q结点
	}
} //DelLLink_p

int GetLList_p(LNode* l, int pos) {
	int count, i;
	LNode *p, *q;		//p为删除位置之前的结点,q为要删除位置的结点
	if (!l) {
		printf("链表不存在");
		return 0;
	}
	if (pos<1) {
		printf("删除位置不存在");
	}
	p = l->next;		//p --> 头结点
	count = 1;
	while (count<pos && p) {
		p = p->next;
		count++;
	} // p --> 要查找的位置
	return p->data;
} //GetLList_p
void PrintLList(LNode* l) {	//传入参数l为该链表的head
	LNode* s;
	s = l->next;		//s = 链表 head.next 为指针
	while (s) {			//保证s不是链表末尾 即 地址s存在
		printf("%d\t", s->data);
		s = s->next;	//s指针后移,依次打印
	}printf("\n");
} //PrintLList

int main() {
	LNode* L1;
	printf("创建链表: \n");
	L1 = InitLList(5, 15);		//创建low-up的顺序链表,并返回该链表的head给L1
	PrintLList(L1);				
	printf("链表插入操作: \n");
	InsertLList(L1, 5, 555);	//在链表的pos位置插入num结点
	PrintLList(L1);
	printf("链表删除操作: \n");
	DelLLink_p(L1, 6);			//删除链表的pos位置结点
	PrintLList(L1);
	printf("链表查找操作: \n");
	int num_5 = GetLList_p(L1, 5);//查找链表的pos位置结点元素
	printf("%d\n",num_5);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值