#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
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;
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;
}
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_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;
}