#include<stdio.h>
#include<malloc.h>
#include<time.h>
#include<stdlib.h>
#include<math.h>
struct node
{
int data; //elementype表示一种数据类型,可能是int/char等等
struct node *next; //next 指针,用于链表结构指向下一个节点
};
typedef struct node node; //重定义struct node类型为node
int GetMidNode(node* L);
void List(node* head);
node* Creat(int Count);
int Length(node *L);
int main()
{
node* head;
// head = Creat(20);
// List(head);
// printf("%d",Length(head));
// printf("%d",GetMidNode(head));
int a;
int Num;
printf("1.查看链表\n2.创建链表\n3.链表长度\n4.中间节点值\n0.退出\n");
while(1)
{
scanf("%d",&a);
switch(a)
{
case 1:
printf("List:\n");
List(head);
printf("\n");
break;
case 2:
printf("输入创建链表节点数:\n");
scanf("%d",&Num);
head = Creat(Num);
printf("\n");
break;
case 3:
printf("链表长度:\n");
printf("%d",Length(head));
printf("\n");
break;
case 4:
printf("中间节点值:\n");
printf("%d",GetMidNode(head));
printf("\n");
break;
case 0:
return 0;
}
}
return 0;
}
int n;
node* Creat(int Count)
{
node *p1,*p2,*head;
n = 0;
srand(time(NULL));//生成种子
p1 = p2 = (node*)malloc(sizeof(node));
// scanf("%d",&p1->data);
p1->data = rand()%1000;
head = NULL;
while(n < Count)
{
n = n+1;
if(n == 1)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
p1 = (node*)malloc(sizeof(node));
// scanf("%d",&p1->data);
p1->data = rand()%1000;
}
p2->next = NULL;
return(head);
}
void List(node* head)
{
node *p1;
p1 = head;
while(p1!= NULL)
{
printf("%d\n",p1->data);
p1 = p1->next;
}
}
int GetMidNode(node* L)
{
int a;
node *search,*mid;
mid = search = L;
while(search->next != NULL)
{
if(search->next->next != NULL)
{
search = search->next->next;
mid= mid->next;
}
else
{
search = search->next;
}
}
a = mid->data;
return a;
}
int Length(node *L)
{
int n = 0;
while(L->next!= NULL)
{
n++;
L = L->next;
}
n++;
return n;
}
运行结果: