16讲链表的创建和显示
#include<stdio.h>#include<string.h>
#include<stdlib.h>
#include<time.h>
#define error 0
#define ok 1
#define true 1
#define false 0
typedef int Status;
typedef int Elemtype;
typedef struct Node
{
Elemtype data;
struct Node *next;
}Node;
typedef struct Node* Linklist; //指向节点类型的指针,用linklist表示。
/*将子函数写在主函数上面就可以不同写声明。原因在于程序从上至下开始执行。
Status initlist_l(Linklist *L);
Status listlengh(Linklist L);
Status creatlist(Linklist *L, Elemtype n);
Status show(Linklist L);
Status getmidnode(Linklist L);
*/
Status initlist_l(Linklist *L)//初始化链表
{
*L = (Linklist)malloc(sizeof(Node)); //产生头结点,病史L指向头结点
if(!(*L))
{
return error;
}
(*L)->next = NULL;
return ok;
}
Status listlengh(Linklist L)//链表长度
{
Elemtype i = 0;
Linklist p = L->next;
while (p)
{
i++;
p = p->next;
}
return i;
}
Status creatlist(Linklist *L, Elemtype n)//创建链表
{
Elemtype i = 0;
Linklist p;
*L = (Linklist)malloc(sizeof(Node));
(*L) -> next = NULL;
srand(time(0)); //播种
for(i=0; i<n; i++)
{
p = (Linklist)malloc(sizeof(Node));
p ->data = rand()%100 +1; //取1-100的随机数
p->next = (*L)->next;
(*L)->next = p;
}
return ok;
}
Status show(Linklist L)//显示链表元素
{
Linklist p = L->next;
while(p)
{
printf("%d\t", p->data);
p = p-> next;
}
printf("\n");
return ok;
}
Status getmidnode(Linklist L)//获得中间节点的值
{
Linklist mid;
Linklist fast;
mid = fast = L;
while (fast->next != NULL)
{
if(fast ->next ->next != NULL)
{
fast = fast ->next ->next;
mid = mid->next;
}
else
{
fast = fast->next;
}
}
return mid->data;
}
int main()
{
Elemtype n = 10, i ;
Linklist L; //作为头结点,
char ch;
int op;
i = initlist_l(&L);
printf("初始化L后,链表长度为%d\n", listlengh(L));
printf("1.创建链表\n2.查看链表\n3.链表长度\n4.中间节点值\n0.退出\n");
while (op != 0)
{
scanf("%d", &op);
while ((ch = getchar()) != EOF && ch != '\n') //文件末尾或者确定键(stdin输入的)
{
;
} ///清除缓存区的确定键
switch(op)
{
case 1:
creatlist(&L, n);
show(L);
break;
case 2:
show(L);
break;
case 3:
printf("链表长度为:%d\n", listlengh(L));
break;
case 4:
printf("中间节点的值为:%d\n", getmidnode(L));
break;
case 0:
exit(0);
default:
printf("请重新输入选项(仅限0-4):");
}
}
return 0;
}
页:
[1]