单链表
单链表的各种操作
#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct LNode
{
ElemType date;
struct LNode* next;
}LinkNode;
void CreateListF(LinkNode * & L,ElemType a[],int n)
{
LinkNode* s;
L = (LinkNode*)malloc(sizeof(LinkNode));
L->next = NULL;
for (int i = 0; i < n; i++)
{
s = (LinkNode*)malloc(sizeof(LinkNode));
s->date = a[i];
s->next= L->next;
L->next = s;
}
} //建立单链表(头插法)
void CreateListR(LinkNode*& L, ElemType a[], int n)
{
LinkNode* s, * r;
L = (LinkNode*)malloc(sizeof(LinkNode));
r = L;
for (int i = 0; i < n; i++)
{
s = (LinkNode*)malloc(sizeof(LinkNode));
s->date = a[i];
r->next = s;
r = s;
}
r->next = NULL;
} //建立单链表尾插法
void InitList(LinkNode*& L)
{
L = (LinkNode*)malloc(sizeof(LinkNode));
L->next = NULL;
} //初始化线性表
void DestoryList(LinkNode*& L)
{
LinkNode* pre = L, * p = L->next;
while (p != NULL)
{
free(pre);
pre = p;
p = pre->next;
}
free(pre);
} //销毁线性表
bool ListEmpty(LinkNode* L)
{
return(L->next == NULL);
} //判断是否为空
int ListLength(LinkNode* L)
{
int n = 0;
LinkNode* p = L;
while (p->next!=NULL)
{
n++;
p = p->next;
}
printf("\n");
} //求线性表长度
void DispList(LinkNode* L)
{
LinkNode* p = L->next;
while (p!=NULL)
{
printf("%d", p->date);
p = p->next;
}
printf("\n");
} //输出线性表
bool GetElem(LinkNode* L, int i, ElemType& e)
{
int j = 0;
LinkNode* p = L;
if (i <= 0)return false;
while (j<i&&p!=NULL)
{
j++;
p = p->next;
}
if (p == NULL)
return false;
else
{
e = p->date;
return true;
}
} //求线性表中某个元素的值
int LocateList(LinkNode* L, ElemType e)
{
int i = 1;
LinkNode* p = L->next;
while (p != NULL && p->date != e)
{
p = p->next;
i++;
}
if (p == NULL)
return(0);
else
return(i);
} //按元素值查找
bool ListInsert(LinkNode*& L, int i, ElemType e)
{
int j = 0;
LinkNode* p = L, * s;
if (i <= 0)return false;
while (j < i - 1 && p != NULL)
{
j++;
p = p->next;
}
if (p == NULL)
return false;
else
{
s = (LinkNode*)malloc(sizeof(LinkNode));
s->date = e;
s->next = p->next;
p->next = s;
return true;
}
} //插入数据元素
bool ListDelete(LinkNode*& L, int i, ElemType& e)
{
int j = 0;
LinkNode* p = L, * q;
if (i <= 0)return false;
while (j < i - 1 && p != NULL)
{
j++;
p = p->next;
}
if (p == NULL)
return false;
else
{
q = p->next;
if (q == NULL)
return false;
e = q->date;
p->next = q->next;
free(q);
return true;
}
} //删除数据元素