腾讯面试题、快慢指针、初始链表、随机创建、打印、查找中间点
代码:#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXSIZE 20
typedef struct like
{
int F;
struct like *next;
}like, *likes;
void explainList();
void InitList(likes *T); //初始化链表
void GetList(likes *T); //创建20个随机数据
void PutList(like *T); //打印所有链表数据
void MiddleList(like *T); //快慢指针查询中间点
void MiddleList(like *T)
{
like *temp = T;
while (1)
{
if (temp->next == NULL)
{
printf("此链表为基数中间点数据为%d", T->F);
break;
}
else if(temp->next->next == NULL)
{
printf("此链表为偶数中间点数据为%d和%d", T->F, T->next->F);
break;
}
T = T->next;
temp = temp->next->next;
}
}
void PutList(like *T)
{
while (1)
{
printf("<%d>", T->F);
if (T->next == NULL)
{
break;
}
T = T->next;
}
}
void GetList(likes *T)
{
int i;
like *temp, *tail;
srand((unsigned)time(NULL));
for (i = 0; i < MAXSIZE; i++)
{
temp = (likes )malloc(sizeof(like ));
temp->F = (rand() % 100);
temp->next = NULL;
if ((*T)->next == NULL)
{
(*T)->next = temp;
}
else
{
tail->next = temp;
}
tail = temp;
}
}
void InitList(likes *T)
{
*T = (likes )malloc(sizeof(like ));
(*T)->next = NULL;
}
void explainList()
{
printf("1、初始化链表\n");
printf("2、创建20个数据\n");
printf("3、打印链表所有数据\n");
printf("4、快慢指针查询中间点\n");
printf("0、结束本程序\n");
}
int main()
{
int K;
like *T;
explainList();
while(1)
{
printf("输入选项:");
scanf("%d", &K);
getchar();
switch(K)
{
case 1:{
InitList(&T);
}
break;
case 2:{
GetList(&T);
}
break;
case 3:{
PutList(T->next);
putchar('\n');
}
break;
case 4:{
MiddleList(T->next);
putchar('\n');
}
break;
case 0:{
return 0;
}
break;
}
}
return 0;
}
页:
[1]