#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;
}
单链表 --头插法尾插法(函数中输入)(自用)
于 2022-03-18 10:32:18 首次发布