1.编写函数,对给定的整数数组a(数组长度和元素个数均为N)进行判定:是否存在某个整数a[i](0<i<N),等于在其之前的所有整数的和
#include <stdio.h>
#include <stdbool.h>
bool judge(int *a,int n) {
for(int i=0; i<n; i++) {
int sum=0;
for(int j=0; j<i; j++)
sum+=a[j];
if(sum==a[i])
return true;
}
return false;
}
int main() {
int a[]= {2,21,1,4,5};
printf("%d",judge(a,5));
}
2.(2x+3y)^n 求第k项余数,例如(2x+3y)^3 = 8x^3 + 36x^2y + 54xy^2 + 27y^3,第二项系数为54,要求递归求第k项余数,不可使用全局遍历
#include <stdio.h>
int find(int n,int k) {
if(n-k==0&&k==0)
return 1;
if(n-k==0)
return 3*find(n-1,k-1);
if(k==0)
return 2*find(n-1,k);
return 2*find(n-1,k)+3*find(n-1,k-1);
}
3.每个教师的信息卡片包括教工号,姓名,性别,入职年份(限定为1900-2100之间的整数)四项,定义存储教师信息的单向链表的节点类型:编写函数,由当前目录下文件名为input.txt的文件依次读入n(n>=1)个教师的信息,创建一个用于管理教师信息的单向链表。
#include <stdio.h>
#include <stdlib.h>
typedef struct teacher {
int num;
char name[20];
int sex;
int year;
struct teacher *next;
} teacher;
struct teacher *create(int n) {
FILE *file;
if((file=fopen("input.txt","r"))==NULL) {
printf("open error");
exit(0);
}
struct teacher *head = (struct teacher *)malloc(sizeof(struct teacher));
head->next=NULL;
for(int i=0; i<n; i++) {
struct teacher *p = (struct teacher *)malloc(sizeof(struct teacher));
fscanf(file,"%d %s %d %d",&p->num,&p->name,&p->sex,&p->year);
p->next=head->next;
head->next=p;
}
return head->next;
}
struct teacher *bubble(struct teacher *head) {
struct teacher *p=head,*q,*tail;
int n;
while(p->next!=NULL) {
n++;
p=p->next;
}
for(int i=0; i<n-1; i++) {
q=head->next;
p=q->next;
tail=head;
for(int j=0; j<n-i-1; j++) {
if(q->num>p->num) {
q->next=p->next;
p->next=q;
tail->next=p;
}
tail=tail->next;
q=tail->next;
p=q->next;
}
}
}
struct teacher *del(struct teacher *head, int key) {
struct teacher *p = head, *q;
while (p != NULL) {
q = p->next;
if (q != NULL && q->num == key) {
p->next = q->next;
struct teacher *temp=q;
free(temp);
}
p = p->next;
}
return head;
}
struct teacher *insert(struct teacher *head) {
struct teacher *p=(struct teacher *)malloc(sizeof(struct teacher));
struct teacher *q=head;
scanf("%d %s %d %d",&p->num,&p->name,&p->sex,&p->year);
while(q->next!=NULL&&q->next->num<p->num)
q=q->next;
p->next=q->next;
q->next=p;
return head;
}
4.定义单链表(每个结点包含2个字段:整数信息,后继指针),编写函数,删除该单链表中所含整数信息等于整数x的多个重复结点。
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
struct node *del(struct node *head, int key) {
struct node *p = head, *q;
while (p != NULL) {
q = p->next;
if (q != NULL && q->data == key) {
p->next = q->next;
struct node *temp=q;
free(temp);
}
p = p->next;
}
return head;
}