链表的插入与删除

#include <stdio.h>
#include <stdlib.h>
typedef struct LNode {
	int data;
	struct LNode* next;
}LNode,*LinkList;

//初始化(有头节点)
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-1 ) {
		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;
}

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;
}

void print(LinkList L) {
	LNode* p = L->next;
	while (p != NULL) {
		printf("The content is %d\n", p->data);
		p = p->next;
	}
}
bool ListInsert(LinkList& L, int i, int e) {
	LNode* p = GetElem(L, i);
	if (p == NULL)
		return false;
	LNode* q = (LNode*)malloc(sizeof(LNode));
	q->data = e;
	q->next = p->next;
	p->next = q;
	return true;
}
bool InsertPriorNode(LNode* p, int e) {
	if (p == NULL) {
		return false;
	}
	LNode* q = (LNode*)malloc(sizeof(LNode));
	q->next = p->next;
	p->next = q;
	q->data = p->data;
	p->data = e;
	return true;
}
bool InsertPriorNode(LNode* p, LNode* q) {
	if (p == NULL|| q == NULL) {
		return false;
	}
	q->next = p->next;
	p->next = q;
	int temp = p->data;
	p->data = q->data;
	q->data = temp;
	return true;
}
bool ListDelete(LinkList& L, int i,int &e) {
	LNode* p = GetElem(L, i);
	if (i < 1 || p == NULL) {
		return false;
	}
	LNode* q = p->next;
	e = q->data;
	p->next = q ->next;
	free(q);
	return true;
}
int main() {
	LinkList L1;
	if (InitList_H(L1)) {
		printf("The List was initialized successfully\n");
	}
	else {
		printf("List initialization failed\n");
	}
	ListTailInsert(L1);
	printf("Before insertion\n");
	print(L1);
	ListInsert(L1, 2, 9);
	printf("After insertion\n");
	print(L1);
	//Node* q = (LNode*)malloc(sizeof(LNode));
	//->data = 9;
	//nsertPriorNode(GetElem(L1, 3), q);
	//printf("lllllllllllllllllllllll\n");
	//print(L1);
	int x;
	ListDelete(L1, 2, x);
	printf("The deleted number is %d\n", x);
	printf("After delete\n", x);
	print(L1);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值