线性表、检查是否有环、逐个、快慢指针
对不对就这么着了往下学(蒙圈中)#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXSIZE 12
typedef struct Like
{
int T;
struct Like *next;
}Like, *Likes;
void Explain(); //程序说明
void InitList(Likes *E); //初始化程序创建头节点
void HeadList(Likes *E); //头插法创建链表(无环)
void TailList(Likes *E); //尾插法创建链表(有环)
void AbFiList(Like *E); //逐个查找链表中是否有环
void AaFiList(Like *E); //快慢指针查找链表中是否有环
void AaFiList(Like *E) //快慢指针查找链表中是否有环
{
Like *temp = E->next, *temps = E->next;
while(temp != NULL && temps != NULL )
{
temp = temp->next;
temps = temps->next->next;
printf("%d<->%d\n", temp->T, temps->T);
if(temp == temps)
{
return;
}
}
}
void AbFiList(Like *E) //逐个查找链表中是否有环
{
Like *temp = E->next->next, *temps;
while(temp != NULL)
{
temps = temp;
do
{
temps = temps->next;
if(temps == temp)
{
printf("已找到环其存在与%d\n", temp->T);
return;
}
}while(temps != NULL || temps != E->next);
temp = temp->next;
}
if(temp == NULL)
{
printf("本链表是个无环链表\n");
}
}
void TailList(Likes *E) //尾插法创建链表(有环)
{
Like *temp, *tail;
srand((unsigned)time(NULL));
for(int i = 0; i < MAXSIZE; i++)
{
temp = (Likes )malloc(sizeof(Like ));
temp->T = (rand() % 100);
temp->next = (*E)->next;
if((*E)->next == *E)
{
(*E)->next = temp;
}
else
{
tail->next = temp;
}
tail = temp;
}
(*E)->next = tail;
temp = (*E)->next->next;
printf("尾插法:");
do
{
printf("<%d>", temp->T);
temp = temp->next;
}while(temp != (*E)->next->next);
putchar('\n');
tail->next = tail->next->next->next;
}
void HeadList(Likes *E) //头插法创建链表(无环)
{
Like *temp;
srand((unsigned)time(NULL));
for(int i = 0; i < MAXSIZE; i++)
{
temp = (Likes )malloc(sizeof(Like ));
temp->T = (rand() % 100);
if((*E)->next == *E)
{
(*E)->next = temp;
temp->next = NULL;
}
else
{
temp->next = (*E)->next;
(*E)->next = temp;
}
}
temp = (*E)->next;
printf("头插法:");
do
{
printf("<%d>", temp->T);
temp = temp->next;
}while(temp != NULL);
putchar('\n');
}
void InitList(Likes *E) //初始化程序创建头节点
{
Like *temp, *temps;
if(*E != NULL)
{
temp = (*E)->next;
do
{
temps = temp;
temp = temp->next;
if(temp == NULL)
{
break;
}
free(temps);
}while((*E)->next != temp); //放在这里temp != NULL 编译会出现错误所以在temp=temp->next下面加上了一个if语句
}
else
{
*E = (Likes )malloc(sizeof(Like ));
}
(*E)->next = *E;
}
void Explain() //程序说明
{
printf("1、初始化程序创建头节点\n");
printf("2、创建头插法无环链表\n");
printf("3、创建尾插法有环链表\n");
printf("4、逐个查找链表中是否有环\n");
printf("5、快慢指针查找链表中是否有环\n");
printf("9、打印两个链表\n");
printf("0、结束本程序\n");
}
int main()
{
int i;
Like *F = NULL;
Explain();
while(1)
{
printf("输入选项:");
scanf("%d", &i);
getchar();
switch(i)
{
case 1:{
InitList(&F);
}
break;
case 2:{
HeadList(&F);
}
break;
case 3:{
TailList(&F);
}
break;
case 4:{
AbFiList(F);
}
break;
case 5:{
AaFiList(F);
}
break;
case 0:{
return 0;
}
break;
default :{
printf("你输入的选项不在可选范围内请仔细阅读说明\n");
}
}
}
return 0;
}
页:
[1]