#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;
}
链表的插入与删除
最新推荐文章于 2023-07-31 16:48:13 发布