#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#define Maxsize 1000
typedef int Elemtype;
typedef int Status;
typedef struct node
{
Elemtype data;
struct node *next;
}Node;
typedef struct node *Linklist;
Status CreatListHead(Linklist *L,int n);
Status Getmidnode(Linklist L,Elemtype *e);
Status CreateListTail(Linklist *L,int n);
void PrintfList(Linklist L);
int ListLength(Linklist L);
int main(void)
{
Linklist L,L1;
Elemtype i,j;
char ch;
printf("1:头插法创建单链表\n2:尾插法创建单链表\n(输入0退出)\n");
while(ch != '0')
{
scanf("%c",&ch);
switch(ch)
{
case '1':
CreatListHead(&L,6);
PrintfList(L);
ListLength(L);
Getmidnode(L,&i);
break;
case '2':
CreateListTail(&L1,9);
PrintfList(L1);
ListLength(L1);
Getmidnode(L1,&j);
break;
case '0':
exit(0);
break;
}
}
return 0;
}
Status CreatListHead(Linklist *L,int n)
{
Linklist temp;
int i;
srand(time(0));
*L = (Linklist)malloc(sizeof(Node));
if(!(*L))
{
return 0;
}
(*L)->next = NULL;
for(i = 0; i < n ;i++)
{
temp = (Linklist)malloc(sizeof(Node));
temp->data = rand()%100 + 1;
temp->next = (*L)->next;
(*L)->next = temp;
}
return 1;
}
Status CreateListTail(Linklist *L,int n)
{
Linklist temp,temp1;
int i;
*L = (Linklist)malloc(sizeof(Node));
if(!(*L))
{
printf("尾插法内存分配失败\n");
exit(1);
}
(*L)->next = NULL;
temp1 = *L;
for(i = 0;i < n;i++)
{
temp = (Linklist)malloc(sizeof(Node));
temp->data = i;
temp->next = temp1->next;
temp1->next = temp;
temp1 = temp;
}
temp1->next = NULL;
return 0;
}
Status Getmidnode(Linklist L,Elemtype *e)
{
Linklist search , mid;
search = mid = L;
while(search->next != NULL)
{
mid = mid->next;
if(search->next->next != NULL)
{
search = search->next->next;
}
else
{
search = search->next;
}
}
*e = mid->data;
printf("当前链表中间结点的值为:%d\n",*e);
return 0;
}
void PrintfList(Linklist L)
{
Linklist temp = L;
while(!(temp->next == NULL))
{
temp = temp->next;
printf("%d ",temp->data);
}
putchar('\n');
}
int ListLength(Linklist L)
{
Linklist temp = L;
int count = 0;
while(temp->next != NULL)
{
temp = temp ->next;
count++;
}
printf("该链表长度为:%d\n",count);
return count;
}
快慢指针练习
最新推荐文章于 2022-08-21 11:46:59 发布