#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef int EleType;
typedef struct LNode {
EleType data;
struct LNode* next;
}LNode;
LNode* ListInsert(LNode* &L) {//头插法创建链表
int x;
LNode* q;
L = (LNode*)malloc(sizeof(LNode));
L->next = NULL;
LNode* p = L;
scanf("%d", &x);
while (x != 9999) {
q = (LNode*)malloc(sizeof(LNode));
q->data = x;
q->next= p->next;
p->next = q;
scanf("%d", &x);
}
return L;
}
LNode* ListInsert2(LNode*& L) {//尾插法
int x;
L = (LNode*)malloc(sizeof(LNode));
LNode* q;
LNode* p= L;
scanf("%d", &x);
while (x != 9999) {
q= (LNode*)malloc(sizeof(LNode));
q->data = x;
p->next = q;
p = q;
scanf("%d", &x);
}
p->next = NULL;
return L;
}
//按序号查找节点值
LNode* GetElem(LNode* L,int i) {
int j = 1;//计数,当不断循环j++,等于i时终止循环,返回数值
LNode* p = L->next;//使p指向空头节点的下一个,也就是我们定义的所谓第一个节点
if (i == 0) {
return L;
}
if (i < 1) {
return NULL;
}
while (p&&j<i) {
p = p->next;//未循环到所指定序号的节点时,p指针不断指向下一个节点
j++;//终止循环判断
}
return p;//返回指向序号指定值的指针,因此主函数中还需要p->data;来提取指针存放地址中的值
}
//按值查找是否存在节点值
LNode* LocateElem(LNode*L,int i) {
LNode* p = L->next;
while (p != NULL && p->data != i) {
p = p->next;
}
return p;
}
//插入节点值(只需拿到待插入节点的前一个节点即可)
LNode* ListFrontInsert(LNode* L, int index,int value) {
LNode* p = GetElem(L, index - 1);//拿到待插入节点前的指针
if (NULL == p) {
return 0;
}
LNode* s = (LNode*)malloc(sizeof(LNode));//申请一个新空间给待插入节点
s->data = value;
s->next = p->next;
p->next = s;
return L;
}
//删除节点
bool ListDelet(LNode *L,int index) {
LNode* p = GetElem(L, index - 1);
if (NULL==p) {
return false;
}
LNode* s = p->next;;//定义一个指针,指向待删除的节点
if (s == NULL) {
return false;//要删除的位置不存在
}
p->next = s->next;
free(s);
return true;
}
void ListPrint(LNode* L) {
L = L->next;
printf("The LinkList Created is:");
while (L != NULL) {
printf("%-4d", L->data);
L = L->next;
}
printf("\n");
}
int main() {
LNode* L=NULL;
//ListInsert(L);
ListInsert2(L);//5 6 8 1 2 9999
//按序号查找
int i;
LNode* search;
printf("Enter the index of LNode you want find: \n");
scanf("%d", &i);
search =GetElem(L, i);
if (search) {
printf("operate successful,the index of LNode you want find's value is: %d\n", search->data);
}
else {
printf("GG\n");
}
//按值查找
int x;
LNode* index;
printf("Enter the value of LNode you want find: \n");
scanf("%d", &x);
index = LocateElem(L,x);
if (index) {
printf("operate successful,the value of LNode you want find's index is: %d\n",index->data);
}
else {
printf("GG\n");
}
//插入节点值
//ListFrontInsert(L, 2, 60);
bool ret;
ret=ListDelet(L, 3);
if (ret) {
printf("Delete sucessful\n");
}
else {
printf("GG\n");
}
ListPrint(L);
return 0;
}
单链表的查找和删除
最新推荐文章于 2023-10-12 12:16:51 发布