单链表 --头插法尾插法(函数中输入)(自用)

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
//3 4 5 6 7 9 10 -9999
typedef int ElemType;
typedef struct LNode {
	ElemType data;
	struct LNode* next;
}LNode,*Linklist;
Linklist List_HeadInsert(Linklist& L)
{
	Linklist p;
	ElemType x;
	L = (Linklist)malloc(sizeof(LNode));
	L->next = NULL;
	scanf("%d", &x);
	while (x != -9999)
	{
		p = (Linklist)malloc(sizeof(LNode));
		p->data = x;
		p->next = L->next;
		L->next = p;
		scanf("%d", &x);
	}
	return L;
}
Linklist List_TailInsert(Linklist& L)
{
	ElemType x;
	L = (Linklist)malloc(sizeof(LNode));
	L->next = NULL;
	Linklist s, r=L;
	scanf("%d", &x);
	while (x != -9999)
	{
		s = (Linklist)malloc(sizeof(LNode));
		s->data = x;
		r->next = s;
		r = s;
		scanf("%d", &x);
	}
	r->next = NULL;
	return L;
}
void List_print(Linklist L)
{
	L = L->next;
	while (L != NULL)
	{
		printf("%4d", L->data);
		L = L->next;
	}
	printf("\n");
}
Linklist GetElem(Linklist L, ElemType i)
{
	int j = 1;
	if (0 == i)
	{
		return L;
	}
	if (i < 1) return NULL;
	Linklist p = L->next;//此处不需要存储数据所以不需要malloc
	while (p && j < i)
	{
		p = p->next;
		j++;
	}
	return p;
}
Linklist locateElem(Linklist L, ElemType e)
{
	Linklist p = L->next;
	while (p && p->data != e)
	{
		p = p->next;
	}
	return p;//有则返回相应地址,无则说明遍历完此时p中为NULL,所以可直接返回p
}
bool Link_frontInsert(Linklist& L, int i, ElemType e)
{
	Linklist p = GetElem(L, i - 1);
	if (NULL == p) return false;
	Linklist s = (Linklist)malloc(sizeof(LNode));
	s->data = e;
	s->next = p->next;
	p->next = s;
	return true;
}
bool LinkDelete(Linklist&L, int i)
{
	Linklist p = GetElem(L, i - 1);
	if (NULL == p|| p->next==NULL) return false;///注意此处与王道书不同
	Linklist q = p->next;
	p->next = q->next;
	free(q);
	q = NULL;
	return true;
	
}
int main()
{
	Linklist L;
	//List_HeadInsert(L);
	//List_print(L);
	List_TailInsert(L);
	List_print(L);
	Linklist search;
	search = GetElem(L, 3);
	if (search)
	{
		printf("GetElem successful,Elem = %d\n", search->data);
	}
	else printf("GetElem fail\n");
	search = locateElem(L, 4);
	if (search)
	{
		printf("locateElem successful,Elem = %d\n", search->data);
	}
	else printf("locateElem fail\n");
	bool ret = Link_frontInsert(L, 8, 99);
	if (ret)
	{
		printf("frontInsert successful\n");
		List_print(L);
	}
	else printf("frontInsert fail\n");
	ret = LinkDelete(L, 1);
	if (ret)
	{
		printf("Delete successful\n");
		List_print(L);
	}
	else printf("delete fail\n");

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值