单链表的各种基本运算和整体建表算法(假设单连表的元素类型ElemType为char),并在此基础上设计一个程序
完成以下功能。
(1)初始化单链表h。
(2)依次采用尾插法插入
(3)输出单链表h。
(4)输出单链表h的长度。
(5)判断单链表h是否为空。
(6)输出单链表h的第3个元素。
(7)输出元素a的位置。
(8)在第4个元素位置上插入f元素。
(9)输出单链表h。
(10)删除单链表h的第3个元素。
(11)输出单链表h。
(12)释放单链表h。
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef char ElemType;
typedef struct LNode
{
ElemType data;
struct LNode* next;
}LNode, * Link;
void CreatList(LNode*& h) //创建单链表
{
h = (LNode*)malloc(sizeof(LNode));
assert(h); //判断这个指针是否为空,空则报错
h->next = NULL; //创建头节点,将next域置空
}
void DestoryList(LNode*& h) //销毁链表
{
LNode* pre, * p;
pre = h; p = h->next;
while (p != NULL)
{
free(pre);
pre = p;
p = pre->next;
}
free(pre);
}
int ListEmpty(LNode* h) //判断是否为空表
{
return(h->next == NULL); //空表返回1,非空0
}
int ListLength(LNode* h) //求链表长度
{
int i = 0;
LNode* p;
p = h;
while (p->next != NULL)
{
p = p->next;
i++;
}
return i;
}
int GetElem(LNode* h, int n, ElemType& e) //按序号求元素
{
int i = 0;
LNode* p;
p = h;
if (n <= 0) //n输入错误
return 0;
while (i < n && p != NULL)
{
p = p->next;
i++;
}
if (p != NULL) //存在第i个数据结点
{
e = p->data;
return 1;
}
else
return 0;
}
int LocateElem(LNode* h, ElemType e) //按元素值查找
{
int i = 1;
LNode* p;
p = h->next;
while (p != NULL && p->data != e)
{
p = p->next;
i++;
}
if (p != NULL) //存在值为e的结点
return i;
else
return 0;
}
int ListInsert(LNode*& h, int i, ElemType e) //插入元素
{
int j = 0;
LNode* p = h, * s;
if (i <= 0)
return 0;
while (j < i - 1 && p != NULL) //找第i-1个结点
{
p = p->next;
j++;
}
if (p == NULL) //为找到第i-1个结点
return 0;
else
{ //插入新结点
s = (LNode*)malloc(sizeof(LNode));
assert(s);
s->data = e;
s->next = p->next;
p->next = s;
}
return 1;
}
int ListDelete(LNode*& h, int i, ElemType& e) //删除第i个元素
{
LNode* p = h, * s;
int j = 0;
if (i <= 0) //i输入错误
return 0;
while (j < i - 1 && p != NULL) //找第i-1个结点
{
p = p->next;
j++;
}
if (p == NULL) //未找到第i-1个结点
return 0;
else
{
s = p->next;
if (s == NULL) //不存在第i个结点
return 0;
else
{
e = s->data;
p->next = s->next;
free(s);
return 0;
}
}
}
void Print(LNode* h) //输出链表
{
LNode* p = h->next;
while (p != NULL)
{
printf("%c", p->data);
p = p->next;
printf(" ");
}
printf("\n");
}
int main()
{
ElemType n, m;
LNode* h;
printf("(1)初始化单链表h\n");
CreatList(h);
printf("(2)依次采用尾插法插入a,b,c,d,e\n");
ListInsert(h, 1, 'a');
ListInsert(h, 2, 'b');
ListInsert(h, 3, 'c');
ListInsert(h, 4, 'd');
ListInsert(h, 5, 'e');
printf("(3)输出单链表h:");
Print(h);
printf("(4)输出单链表长度:%d\n", ListLength(h));
printf("(5)判断单链表是否h为空:%s\n", (ListEmpty(h) ? "空" : "非空"));
GetElem(h, 3, n);
printf("(6)输出单链表h第3个元素:%c\n", n);
printf("(7)输出元素a的位置:%d\n", LocateElem(h, 'a'));
printf("(8)在第4个元素位置上插上f元素\n");
ListInsert(h, 4, 'f');
printf("(9)输出单链表h:");
Print(h);
printf("(10)删除单链表h第3个元素\n");
ListDelete(h, 3, m);
printf("(11)输出单链表h:");
Print(h);
printf("(12)释放单链表h");
DestoryList(h);
}
运行结果