一、单链表应用
创建的单链表,实现图书信息的添加,打印功能。
#include<stdio.h>
#include<stdlib.h>
struct Book{
char title[200];
char author[40];
struct Book *next;
};
void getInput(struct Book *book){
printf("请输入书名");
scanf("%s",book->title);
printf("请输入作者");
scanf("%s",book->author);
}
void insertBook(struct Book **libary){
struct Book *book,*temp;
book=(struct Book *)malloc (sizeof(struct Book));
if(book==NULL)
{
printf("内存分配失败\n");
exit(1);
}
getInput(book);
if(*libary!=NULL){
//先把原来head指向的地址存入临时变量,
//把head指针指向新的元素,新元素指针指向原来元素 的地址
temp=*libary;
*libary=book;
book->next=temp;
}else{
*libary=book;
book->next=NULL;
}
}
void printLibary(struct Book *libary){
struct Book *book;
int count=1;
book=libary;
while(book!=NULL)
{
printf("Book%d",count);
printf("书名 %s",book->title);
printf("作者 %s\n",book->author);
book=book->next;
count++;
}
}
void release(struct Book *libary){
while(libary!=NULL){
free(libary);
libary=libary->next;
}
}
int main(void){
struct Book *libary=NULL;
int ch;
while(1)
{
printf("是否需要录入书籍信息\n");
do{
ch=getchar();
}while(ch!='y' &&ch!='n');
if(ch=='y'){
insertBook(&libary);
}else
{
break;
}
}
printf("请问是否需要打印图书信息(y/n)\n");
do{
ch=getchar();
}while(ch!='y'&&ch!='n');
if(ch='y')
{printLibary(libary);
}
else{
release(libary);
}
}
二、判断闰年
def is_leap(year):
if (year%4==0 and year%100!=0 )or ( year%400==0):
print(year,"是闰年")
else :
print(year,"是平年")
year=2019
is_leap(year)
结果:2019是平年
三、定义函数,函数接收list作为参数,实现冒泡排序
def bubbleSort(arr):
n=len(arr)
for j in range(0,n-1):
for i in range(0,n-1-j):
if arr[i]>arr[i+1]:
arr[i],arr[i+1]=arr[i+1],arr[i]
arr=[12,4,12,5,1,5,34,6,5,7,4]
bubbleSort(arr)
print(arr)
三、定义函数,函数接收list作为参数,实现直接选择排序
def selectSort(arr):
# 简单选择排序: 小->大
for i in range(len(arr)):
min=i
for j in range(i+1,len(arr)):
if arr[j]<arr[min]:
min=j
arr[i],arr[min]=arr[min],arr[i]
return arr
arr=[12,4,12,5,1,5,34,6,5,7,4]
selectSort(arr)
print(arr)
四、实现矩阵转置
#include<stdio.h>
#define row 3
#define col 3
void Tran(int arr[row][col]){
int i,j,temp[row][col];
for(i=0;i<col;i++){
for(j=0;j<row;j++)
temp[i][j]=arr[j][i];
}
for(i=0;i<row;i++){
for(j=0;j<col;j++){
printf("%d ",temp[i][j]);
}
printf("\n");
}
}
int main(void){
int arr[row][col]={{3,4,5},{7,6,5},{1,2,4}};
Tran(arr);
}
五、编写函数递归逆序输出数组元素
def reverse(arr,i,n):
if i>=n:
return
else:
reverse(arr,i+1,len(arr))
print(arr[i])
str=[1,2,3,4]
reverse(str,0,len(str))