编写程序完成如下功能:
(1) 编写一个函数,构造一个包含 n 个随机数的链表,其中 n 由参数输入。
(2) 编写一个函数,输出链表中的所有整数,要求每行输出 k 个整数,每个整数占 n 列,其中 k 和 n 由参数传入。
(3) 编写一个函数,对链表按照从小到大排序。
(4) 编写一个函数,删除链表中包含数字 3 和 5 的节点。
(5) 编写测试程序
/*=================================================================================================
*学号:1527403059
*作业:E72
*功能:1、编写一个函数,构造一个包含n个随机数的链表,其中n由参数输入
2、编写一个函数,输出链表中的所有整数,要求每行输出k个整数,每个整数占n列,其中k,n由参数传入
3、编写一个函数,对链表从小到大排序
4、编写一个函数,删除链表中包含数字3和5的节点
5、编写测试程序
*作者:陆胤任
*日期:2016.1.1
*==================================================================================================*/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
struct Node //声明一个结构体
{
int num;
struct Node *next;
};
/*function define
*@brief:构造一个包含n个随机数的链表,其中n由参数输入
*@param:struct Node *head:头节点
struct Node *p1,*p2:结构体指针
*@reval:struct Node *head:结构体头指针
*/
struct Node *CreatList(int n)
{
int i;
struct Node *head;
struct Node *p1,*p2;
head=(struct Node*)malloc(sizeof(struct Node)); //开辟一个新单元
p2=head;
srand((unsigned)time(NULL));
for(i=0;i<n;i++)
{
p1=(struct Node*)malloc(sizeof(struct Node));
p1->num=rand()%100; //随机初始化结构体
p2->next=p1;
p2=p1;
}
p2->next=NULL;
return head;
}
/*function define
*@brief:输出链表中的所有整数,要求每行输出k个整数,每个整数占n列,其中k,n由参数传入
*@param:int k:每行输出k个数
int n:每个数占n列
*@reval:void
*/
void print_Node(struct Node *head,int k,int n)
{
struct Node *p;
int count=0;
char format[100],buf[10];
itoa(n,buf,10);
strcpy(format,"%");
strcat(format,buf);
strcat(format,"d");
p=head->next;
while(p!=NULL)
{
printf(format,p->num);
count++;
if(count%k==0)
{
printf("\n");
}
p=p->next;
}
}
/*function define
*@brief:对链表从小到大排序
*@param:struct Node *p1,*p2:结构体指针
int temp:用于保存数组
*@reval:*head:结构体头指针
*/
void sort_Node(struct Node *head)
{
struct Node *p1,*p2,*p;
int temp;
p1=head->next;
while(NULL!=p1->next)
{
p=p1;
p2=p1->next;
while(NULL!=p2)
{
if((p->num)>(p2->num))
{
p=p2;
}
p2=p2->next;
}
if(p!=p1)
{
temp=p->num;
p->num=p1->num;
p1->num=temp;
}
p1=p1->next;
}
}
/*function define
*@brief:判断数字是否包含数字3或5
*@param:int k,t
*@reval:flag 1:包含 0:不包含
*/
int ContainNumber(int n)
{
int flag=0;
int k,t;
k=n;
t=n;
do
{
if(k%10==3)
{
do
{
if(t%10==5)
{
return 1;
}
t/=10;
}while(t!=0);
}
k/=10;
}while(k!=0);
return 0;
}
/*function define
*@brief:删除链表中包含数字3和5的节点
*@param:struct Node *head:结构体头指针
struct Node *s,*p:结构体指针
*@reval:struct Node *head:结构体头指针
*/
int min_Node(struct Node *head)
{
struct Node *p,*q;
int flag=0;
q=head;
p=q->next;
while(p!=NULL)
{
if(ContainNumber(p->num)==1)
{
flag=1;
q->next=p->next;
free(p);
p=q->next;
}
q=p;
p=q->next;
}
return flag;
}
int main()
{
struct Node *head;
int n;
int k,l;
int flag;
printf("请输入随机数的个数n:\n");
scanf("%d",&n);
head=CreatList(n);
printf("请输入输出数占几行几列:\n");
scanf("%d%d",&k,&l);
printf("生成的随机列表排序后如下:\n");
sort_Node(head);
print_Node(head,k,n);
flag=min_Node(head);
printf("\n");
if(flag==1)
{
printf("删除数字3和5后的链表为:\n");
min_Node(head);
print_Node(head,k,n);
}
else
{
printf("链表中不包含数字3和5的结点\n");
}
return 0;
}