#include<stdio.h>
#include<malloc.h>
typedef char ElemType;
typedef struct LNode
{
ElemType date;
struct LNode* next;
}LinkNode;
void InitList(LinkNode*& L)//(1)初始化单链表h;
{
L = (LinkNode*)malloc(sizeof(LinkNode));
L->next = NULL;
}
//(2)依次采用尾插法插入a、b、c、e、d元素;
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)//因为要插入到第i个位置所以是i-1
{
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;
}
}
//(3)输出单链表h;
void DispList(LinkNode* L)
{
LinkNode* p = L->next;
while (p != NULL)
{
printf("%c", p->date);
p = p->next;
}
printf("\n");
}
//(4)输出单链表h长度;
int ListLength(LinkNode* L)
{
int j = 0;
LinkNode* p = L;
while (p != NULL)
{
p = p->next;
j++;
}
return(j);
}
//(5)判断单链表h是否为空;
bool ListEmpty(LinkNode* L)
{
return(L->next == NULL);
}
//(6)输出单链表h的第3个元素;
bool GetElem(LinkNode* L, int i, ElemType& e)
{
int j = 0;
LinkNode* p = L;
if (i <= 0)
return false;
while (j < i && p != NULL)
{
p = p->next;
j++;
}
if (p == NULL)
return false;
else
{
e = p->date;
return true;
}
}
//(7)输出元素a的位置;
bool LocateElem(LinkNode* L, ElemType e)
{
int j = 0;
LinkNode* p = L;
while (p->date != e && p != NULL)
{
j++;
p = p->next;
}
if (p == NULL)
return false;
else
{
return j;
}
}
//(10)删除单链表h的第3个元素;
bool ListDelete(LinkNode*& L, int i, ElemType& e)
{
LinkNode* p = L, * s;
int j = 0;
if (i <= 0)
return false;
while (j < i - 1 && p != NULL)
{
j++;
p = p->next;
}
if (p == NULL)
return false;
else
{
s = p->next;
if (s == NULL)
return false;
e = s->date;
p->next = s->next;
free(s);
return true;
}
}
//(12)释放单链表h。
void DestroyList(LinkNode*& L)
{
LinkNode* pre = L, * p = L->next;
while (p != NULL)
{
free(pre);
pre = p;
p = pre->next;
}
free(pre);
}
int main()
{
LinkNode* h;
ElemType e;
printf("单链表的基本运算如下:\n");
printf("(1)初始化单链表h.\n");
InitList(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:");
DispList(h);
printf("(4)输出单链表h的长度:%d\n", ListLength(h));
printf("(5)判断单链表h是否为空:%s\n", (ListEmpty(h) ? "空" : "非空"));
GetElem(h, 3, e);
printf("(6)输出单链表h的第3个元素:%c\n", e);
printf("(7)输出元素a的位置:%d\n", LocateElem(h, 'a'));
printf("(8)在第4个元素位置上插入f元素.\n");
ListInsert(h, 4, 'f');
printf("(9)输出单链表h:");
DispList(h);
printf("(10)删除单链表h的第3个元素.\n");
ListDelete(h, 3, e);
printf("(11)输出单链表h:");
DispList(h);
printf("(12)释放单链表h\n");
DestroyList(h);
}