#include<stdio.h>
#include<stdlib.h>
typedef char ElemType;
typedef struct Node
{
ElemType data;
struct Node *next;
} SqList;
void InitList(SqList *&L)
{
L=(SqList *)malloc(sizeof(SqList));
L->next=NULL;
}
void Insert(SqList *&L,ElemType e)//尾插法 特别关注
{
SqList *s=L,*r;
while(s->next!=NULL)
s=s->next;
r=s;
s=(SqList *)malloc(sizeof(SqList));
r->next=s;
s->data=e;
s->next=NULL;
}
void Print(SqList *&L)
{
SqList *s=L->next;
while(s!=NULL)
{
printf("%c ",s->data);
s=s->next;
}
printf("\n");
}
void PrintLength(SqList *&L)
{
int i=0;
SqList *s=L->next;
while(s!=NULL)
{
s=s->next;
i++;
}
printf("%d\n",i);
}
void PrintData(SqList *&L,int n )
{
int i=0;
SqList *s=L->next;
while(s!=NULL)
{
s=s->next;
i++;
if(i==n-1)
{
printf("%c\n ",s->data);
break;
}
}
}
int Find(SqList *L,ElemType n)
{
int i=0;
SqList *s=L->next;
while(s!=NULL)
{
i++;
if(s->data==n)
break;
s=s->next;
}
return i;
}
bool Insertinto( SqList *&L,int i, ElemType &e)
{
int j=0;
SqList *p=L,*q;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
q=(SqList *)malloc(sizeof(SqList));
q->data=e;
q->next=p->next;
p->next=q;
return true;
}
}
bool Delete(SqList *L,int i)
{
int j=0;
SqList *p=L,*q;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
q=p->next;
if(q==NULL)
return false;
p->next=q->next;
free(q);
return true;
}
}
bool SqNull(SqList *L)
{
if(L->next!=NULL)
return true;
else
return false;
}
int main()
{
SqList *L;
InitList(L); //初始化单链表
ElemType a,b,c,d,e;
scanf("%c %c %c %c %c%*c",&a,&b,&c,&d,&e);
Insert(L,a);
Insert(L,b);
Insert(L,c);
Insert(L,d);
Insert(L,e); //使用尾插法插入元素a,b,c,d,e
Print(L); //输出单链表
PrintLength(L); //输出单链表长度
if(SqNull(L))
printf("单链表不为空\n");
else printf("单链表为空\n"); //判断单链表是否为空
PrintData(L,3); //输出第三个元素
printf("元素a的位置:%d\n",Find(L,a)); //输出元素a的位置
ElemType f;
scanf("%c",&f);
Insertinto(L,4,f); //将f插入到第四个位置
Print(L); //输出单链表
Delete(L,3); //删除第三个元素
Print(L); //输出单链表
free(L); //释放内存
return 0;
}
单链表的基本算法
最新推荐文章于 2023-03-17 23:14:09 发布