#include<stdio.h>
#include<stdlib.h>
#include <string.h>
//注:对原有格式作了一些修改
//节气信息结构
struct SolarTerm{
char name[20];//节气名称
char poem[30];//节气诗句
char author[10]; //诗句作者
};
typedef struct SolarTerm ElementType;
//结点结构体
struct LNode{
ElementType Data;
struct LNode * Next;
};
typedef struct LNode * List;
typedef List Position;
//建立一个带有头结点的空链表
List MakeEmpty(){
List p = (List)malloc(sizeof(LNode));
p->Next = NULL;
return p;
}
// 求表长
int Length(List L){
List p = L->Next;//跳过头指针
int length = 0;
if (p)
{
do
{
length++;
p = p->Next;
}
while(p);
return length;
}
else
{
// printf("链表为空!\n");
return 0;
}
}
//按值查找 按name查找
int Find(List L,ElementType X){
List p = L->Next;
int index = 0;
if (p)
{
do
{
index++;
if ( strcmp(p->Data.name, X.name) == 0 )
{
return index;
}
p = p->Next;
}
while(p);
printf("找不到该元素!\n");
return 0;
}
else
{
printf("链表为空!\n");
return 0;
}
}
//按位序查找 要定义一个链表指针来接收
Position FindKth(List L,int K){
List p = L;
if ( K >= 0 )
{
while (K)
{
p = p->Next;
K--;
}
return p;
}
else
{
printf("输入有误!\n");
return L;
}
}
//插入 带有头结点的单链表 i是指位序 注意i等于1的情况
/**
* 将数据后插到第i-1个结点后面 头指针为0
* */
bool Insert(List L,ElementType X,int i){
//1.找第i-1结点;2.p= 第i-1这个结点的地址;
//3.申请新的结点空间 data赋值
//4. s->Next=p->Next; 5. p->Next=s;
List s;
List p = L;
int j = 0;
while( p && (j<i-1) )//j指到i-1位置或者p已经到最后时跳出
{
p = p->Next;
++j;
}
if(!p||j>i-1)//i<1或者i>ListLength(L)+1时,插入位置无效 不调用ListLength,提高效率
{
printf("插入位置无效!!!\n");
return false;
}
s = (List)malloc(sizeof(LNode));
strcpy(s->Data.name, X.name);
strcpy(s->Data.poem, X.poem);
strcpy(s->Data.author, X.author);
s->Next = p->Next;
p->Next = s;
return true;
}
//删除
bool Delete(List L,int i){
/*LNode* s;*/List p=L;int j=0;
List q;
while(p && (j<i-1))//j指到i-1位置
{
p=p->Next;
++j;
}
if (p == NULL/*nullptr*/||!(p->Next) || j>i - 1)//i<1或者i>ListLength(L)时,删除位置无效
{
printf("删除位置无效!!!\n");
return false;
}
q=p->Next;
p->Next=q->Next;//p->next=p->next->next
free(q);//释放空间
return true;
}
//带头结点的单链表的数据显示
void Display(List L){
Position p=L->Next;
while(p){
printf("%s %s %s\n",p->Data.name,p->Data.poem,p->Data.author);//显示节气名称和对应的诗句 及作者
p=p->Next;
}
printf("\n");
}
//销毁单链表
void Destroy(List L){
while(L->Next){
Position s=L->Next;//2
L->Next=s->Next;//3
free(s);//4
}
free(L);
}
int main(){
//1.创建空的单链表
//2.位置1插入立春节气信息,位置1插入雨水节气信息,位置1插入春分节气信息
//3.删除位置2的元素
//4.查找春分节气 在表中的位序
//5.获取链表中元素的个数
//6.销毁单链表
List L=MakeEmpty();
ElementType Data;
strcpy(Data.name, "立春");
strcpy(Data.poem,"春冬移律吕,天地换星霜 ");
strcpy(Data.author,"唐 元稹 ");
Insert(L,Data,1);
Display(L);
strcpy(Data.name, "雨水");
strcpy(Data.poem,"随风潜入夜,润物细无声 ");
strcpy(Data.author,"唐 杜甫");
Insert(L,Data,1);
Display(L);
strcpy(Data.name, "春分");
strcpy(Data.poem,"春风如贵客,一到便繁华");
strcpy(Data.author,"清 袁枚");
Insert(L,Data,1);
Display(L);
ElementType NewData;
strcpy( NewData.name, "立春");
printf("locate=%d\n",Find(L,NewData));
printf("length=%d\n",Length(L));
Delete(L,2);
Display(L);
Destroy(L);
}