📄 c09_11.c
字号:
#include <stdio.h>
#include <stdlib.h>
/*结点数据类型定义*/
struct Data
{
int num;
struct Data * next;
};
/*定义宏*/
#define LEN sizeof(struct Data)
/*函数声明部分*/
struct Data * insert(struct Data *head, struct Data *stud);
void print(struct Data *head);
int main()
{
struct Data *NewNode; /* 定义一个指针指向插入点 */
int number; /* 定义一个整数表示插入的数 */
struct Data *headpoint; /* 链表的头结点 */
headpoint=NULL;
printf("请输入需要插入的数:输入0结束:\n");
scanf("%d",&number);
while (number!=0)
{
NewNode=(struct Data *)malloc(LEN);
if( !NewNode )
{
printf("内存不足!\n");
return 0;
}
NewNode->num=number;
headpoint=insert(headpoint,NewNode);
printf("请输入需要插入的数:输入0结束。\n");
scanf("%d",&number);
}
printf("插入结束!!!\n");
print(headpoint); /* 调用函数输出链表 */
return 0;
}
/*************************************************
功能:插入一个结点到链表中
返回:返回链表的头指针,因为链表为空,或者结点插入在开头,
头指针指向的地址会变化。
参数:head 是链表头指针
stud 是要插入的结点
**************************************************/
struct Data *insert(struct Data *head, struct Data *p0)
{
struct Data *p1; /* p0插入p1之前、p2之后, 即:p2-->p0-->p2 */
struct Data *p2;
p1 = head;
if (head == NULL) /* 原链表是空表 */
{
head = p0;
p0->next = NULL;
}
else
{
while ((p0->num > p1->num) && (p1->next != NULL)) /*查找待插入位置 */
{
p2 = p1;
p1 = p1->next;
}
if (p0->num <= p1->num) /* num从小到大排列,p0应插入表内(不是表尾) */
{
if (p1 == head) /* p1是表头结点 */
{
head = p0;
p0->next = p1;
}
else
{
p2->next = p0;
p0->next = p1;
}
}
else /* p0插入表尾结点之后 */
{
p1->next = p0;
p0->next = NULL;
}
}
return (head);
}
/* 输出链表中的数据 */
void print(struct Data *head)
{
printf("链表中的数据:\n");
if ( !head )
printf("链表为空!!!\n");
while ( head )
/* 当 head 不为空,此处的head示函数的局部变量,不会影响main()中的head值,
但如果修改head指向的数据,则会影响*/
{
printf("%5d ->",head->num);
head = head->next;
}
printf(" NULL\n");
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -