因为比较简单直接给代码:
<1>.c文件
#include"Module.h"
int main()
{int m = 0;int flag = 0,elect=0;printf("*-----------------------------------------------------------------------------------------*\n");struct STU* List = CreaterList();traversal_List(List);printf("*-----------------------------------------------------------------------------------------*\n\n");while (1){printf("**----------------------------------------------**\n");printf("请选择您想选择的操作:\n");printf("1:插入\t2:退出\t\n");scanf("%d", &elect);switch (elect){case 1:Insert_List(List);traversal_List(List);break; case 2:exit(0);break;default:printf("非法输入请重新操作");break;printf("**----------------------------------------------**\n");}}
}
<2>.h文件
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
typedef struct STU
{int data;//数据域struct STU* next;//指针域,next是指针,指向结构体STU
};//链表打印函数
int traversal_List(struct STU* head)
{printf("列表信息为:");for (struct STU* p = head->next; p != NULL; p=p->next)//链表循环{printf("%d\t",p->data);}printf("\n");return 1;
}//使用尾插法创建一个链表
struct STU* CreaterList()
{//创建头结点struct STU* head = (struct STU*)malloc(sizeof(struct STU));//将分配到的“struct STU”大小的内存转换为struct STU*类型head->next = NULL;struct STU* p = head;//struct STU类型的指针P指向头指针headprintf("请输入你想创建的链表元素个数:\n");int amount = 0;scanf("%d", &amount);for (int i = 0; i<amount; i++){//创建新结点struct STU* knot = (struct STU*)malloc(sizeof(struct STU));//存储数据printf("请输入第%d个元素的数据:\n",i+1);scanf("%d",&knot->data);//将值存放进knot结点中//P指针指向链表新结点knotp->next = knot;//移动指针Pp = p->next;knot->next = NULL;//确保链表最后一个一个结点的指针域指向NULL,否则它会指向一个不定的值p->next = NULL;//确保p->next始终指向链表最后一个结点}return head;//返回头结点
}//链表插入
int Insert_List(struct STU* List)
{int tempt;for (struct STU* p = List->next; p != NULL; p=p->next)//链表循环{//创建新结点struct STU* knot = (struct STU*)malloc(sizeof(struct STU));printf("请输入想插入的元素数据:\n");scanf("%d",&knot->data);//将值存放进knot结点中tempt=knot->data;if(p==NULL){printf("空表!!\n");return 0;}else{for (p = List->next; p != NULL; p=p->next)//链表循环{if((tempt>=p->data)&&(p->next==NULL))//如果输入时输入值大于等于链表中所有值,直接让最后一个链表的指针指向新结点{//并让最新结点的指针指向空p->next = knot;//移动指针Pknot->next = NULL;return 0;}else if((tempt>=p->data)&&(tempt<=p->next->data))//如果输入值大于等于链表某值,但不是其中的最大值时{knot->next = p->next;p->next = knot;return 1;}else if(tempt<p->data)//如果第二个元素小于第一个元素{knot->next = p->next;p = knot;return 1;}}}}
}