C数据结构(文件操作,随机数,排序,栈和队列,图和遍历,最小生成树,最短路径)程序例子

文件操作

文件打开方式

              意义

    ”r”

只读打开一个文本文件,只允许读数据

    ”w”

只写打开或建立一个文本文件,只允许写数据

    ”a”

追加打开一个文本文件,并在文件末尾写数据

    ”rb”

只读打开一个二进制文件,只允许读数据

    ”wb”

只写打开或建立一个二进制文件,只允许写数据

    ”ab”

追加打开一个二进制文件,并在文件末尾写数据

    ”r+”

读写打开一个文本文件,允许读和写

    ”w+”

读写打开或建立一个文本文件,允许读写

    ”a+”

读写打开一个文本文件,允许读,或在文件末追加数据

   

 

1.读取文件“d:\tc20\fact.c”中的数据并显示在屏幕上。

   FILE *fp;   char ch;

   fp = fopen("d:\\tc20\\fact.c", "r");

   if (fp==NULL){

        printf("open file error!\n");

        exit(0);

   }

while(!feof(fp)) {

        ch = fgetc(fp);

        printf("%c",ch);

    }

fclose(fp);

2.例如,编写程序,将从键盘输入前20个字符写入文件“d:\test\char.dat”

#include <stdio.h>

#include <stdlib.h>

int main()

   FILE *fp;   char i = 0, ch;

   fp = fopen("d:\\test\\char.dat", "w");

   if (fp==NULL){

        printf("open file error!\n");

        exit(0);

   }

while(i < 20) {

        ch = getchar();

        fputc(ch,fp);

        i++;

    }

    fclose(fp);

    system("pause");

    return 0;

 }

3.将“d:\tc20\swap.c”复制一份存放在“D:\ test\swapbak.c”

  #include <stdio.h>

int main()

{  FILE *in,*out;   char ch;

   in = fopen("d:\\tc20\\swap. c", "r");

   out = fopen("d:\\test\\swapbak.c", "w");

   if (in==NULL || out==NULL ){

        printf("open file error!\n");

        exit(0);

   }

while(!feof(in)) {

        ch = fgetc(in);

        fputc(ch,out);

    }

    fclose(in);

    fclose(out);

    return 0;

 }

q 常用格式:fgets(字符数组名, n,文件指针)

q n是一个正整数,表示从文件中读出的字符串不超过 n-1个字符。在读入的最后一个字符后加上串结束标志‘\0’

q 在读出n-1个字符之前,若遇到了换行符或EOF,则结束。

q fgets函数的返回值是字符数组的首地址。

q  

q 常用格式:fputs(字符串, 文件指针);写入文件!

q 其中的字符串可以是字符串常量,也可以是字符数组名,或字符指针变量。

4.将“test_time.c”的内容用fgets读取出来并显示在屏幕上

   #define SIZE 1024

int main()

{  FILE *in;   char str[SIZE+1];

   in = fopen("test_time.c", "r");

  

   if (in==NULL){

        printf("open file error!\n");

        exit(0);

   }

while(!feof(in)) {

        fgets(str, SIZE,in);

        puts(str);

    }

    fclose(in);

    system("pause");

    return 0;

 }

F fprintf的返回值为写入的字符个数,fscanf的返回值为读取的数据个数,可作为是否正确完成操作的依据。

F 写入整数或浮点数时,数之间应有间隔

while(!feof(in)) {

  if (fscanf(in, "%d",&a)!=1) break;

       // fscanf(in, "%d",&a);

        b = a * a;

        printf("%8d",b);

        fprintf(out,"%8d",b);

    }

学生信息

while(!feof(in)) {

if (fread(studinfo+i,sizeof(STUDENT), 1, in)!=1) break;

//fread(studinfo+i,sizeof(STUDENT), 1, in);

printf("%s %s %d\n",studinfo[i].Sno,                                   studinfo[i].Sname,studinfo[i].Grade);

i++;

}

fwrite(studinfo, sizeof(STUDENT), i, out);

      fclose(in);

      fclose(out); return 0;

 fseek(文件指针,位移量,起始点);

  • 文件指针”指向被操作的文件。
  •  “位移量”表示指针要移动的字节数,要求位移量是long型数据,以便在文件长度大于64KB 时不会出错。当用常量表示位移量时,要求加后缀“L”。例如,fseek(fp,10L, SEEK_SET)
  •  “起始点”表示从何处开始计算位移量,规定的起始点有三种:文件首( SEEK_SET/0),当前位置( SEEK_CUR/1)和文件尾( SEEK_END/2
  • fseek适用于二进制文件,用于文本文件时,应该令所有数据(整数、浮点数和字符串)以相同的宽度写入。例如,fprintf(out,"%8d",b);

随机数

函数time()返回以秒计算的当前时间值,该值被转换为无符号整数并用作随机数发生器的种子

#include  <time.h>

srand((unsigned)time(NULL));

magic = rand() % 100 + 1;

代码

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

int main()

{

    FILE *fp;

    //建立随机数  并存入文件chen.txt-----

    fp = fopen("d:\\1\\chen.dat", "wb");

    if (fp==NULL){

        printf("open file error!\n");

        exit(0);

    }

    int i,a;

    srand((unsigned)time(NULL));

    for(i=1;i<=1000;++i)

        fprintf(fp,"%8d",rand()%1000+1);

    fclose(fp);

    //重新打开文件  并输出---------    fp = fopen("d:\\1\\chen.dat", "rb");

    if (fp==NULL){

        printf("open file error!\n");

        exit(0);

    }

    while(!feof(fp)) {

        fscanf(fp,"%8d",&a);

        printf("%8d",a);

    }

    printf("\n\n");

 fseek(fp,8*4L,0);fscanf(fp,"%d",&a);printf("%8d",a);

 fseek(fp,8*9L,0);fscanf(fp,"%d",&a); printf("%8d",a);

fseek(fp,8*995L,0);fscanf(fp,"%d",&a);printf("%8d",a);fseek(fp,8*990L,0);fscanf(fp,"%d",&a);printf("%8d",a);

    fclose(fp);

    system("pause");  

}

*******************************************

#include<stdio.h>

#include<stdlib.h>

typedef struct{

              int English;

              int PE;

              int Physics;

              }Grade;

typedef struct {

       char Name[20];

       char Number[8];

       char Sex[6];

       Grade grade;

}StuInfor;

int main()

{

    StuInfor s[5],r[5];

    FILE *fp;

    int i,m;

    fp = fopen("studinfo.dat", "wb");

fp = fopen("d:\\1\\studinfo.dat", "wb");

    if (fp==NULL){

        printf("open file error!\n");

        exit(0);

    }

    for(i=1;i<=5;++i){

        printf("请输入第%d个同学的信息:\n",i);

        printf("请输入姓名:\n");

        fflush(stdin);

        gets(s[i-1].Name);

        printf("请输入学号:\n");

        fflush(stdin);

        gets(s[i-1].Number);

        printf("请输入性别:\n");

        fflush(stdin);

        gets(s[i-1].Sex);

        printf("请输入各科成绩:\n");

        fflush(stdin);

        scanf("%d",&s[i-1].grade.English);

        scanf("%d",&s[i-1].grade.PE);

        scanf("%d",&s[i-1].grade.Physics);

    }

    fwrite(s,sizeof(StuInfor),5,fp);

    fclose(fp);

    fp = fopen("studinfo.dat", "rb");//rb!!!!!

    if (fp==NULL){

        printf("open file error!\n");

        exit(0);

}

printf("姓名  性别  学号  英语成绩   物理成绩   体育成绩\n");

    for(i=0;!feof(fp);i++){

                        if((fread(r+i,sizeof(StuInfor),1,fp))!=1)break printf("%s\t%s\t%s\t%d\t%d\t%d\t\n",r[i].Name,r[i].Sex,r[i].Number,r[i].grade.English,r[i].grade.PE,r[i].grade.Physics);

           }

           fclose(fp);

    system("pause");

    return 0;

}

1.  题目一中要求打开的是二进制文件,对“wb”的应用有所疏忽。

2.  随机数的产生没有记住:#include<time.h>srand((unsigned)time(NULL));rand()%1000+1

3.  程序的灵活性,比如用fseek时输出倒数第5个数可以这样写fseek(fp,8*995L,0)。但是经过老师的指点:fseek(fp,1000-5L,0)。即倒数时为负的数字和1000相加即可。

题目二中fflush(stdin)的作用必须重视

 

 

 

 

 

 

 

 

 

排序

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

#define a1 3000

#define a2 4000

#define a3 3000

int main()

{

    FILE *fp;

    int i,A[a1],B[a2],C[a3];

    clock_t   start,finish;

    //建立随机数  并存入文件intfile.dat------

    fp = fopen("intfile.dat", "w");

    if (fp==NULL){

        printf("open file error!\n");

        exit(0);

    }

    srand((unsigned)time(NULL));

    for(i=1;i<=a1+a2+a3;++i)

        fprintf(fp,"%9d",rand()+1);

    fclose(fp);

    fp = fopen("intfile.dat", "r");

    if (fp==NULL){

        printf("open file error!\n");

        exit(0);

    }

    for(i=0;i<a1;++i)

       fscanf(fp,"%d",&A[i]);

    for(;i<a1+a2;++i)

       fscanf(fp,"%d",&B[i-a1]);

    for(;i<a1+a2+a3;++i)

       fscanf(fp,"%d",&C[i-a1-a2]);

    fclose(fp);

    //冒泡

    start=clock();

    int j,k;

    for(i=1;i<=a1;++i)

        for(j=0;j<a1-i;++j)

            if(A[j]>A[j+1]){

               k=A[j];

               A[j]=A[j+1];

               A[j+1]=k;

            }

    finish=clock();

    for(i=0;i<a1;++i)printf("%d\t",A[i]);

    printf("\n***time***%d\n",finish-start);

    system("pause");

    //简单选择排序

    int r,s;

    start=clock();

    for(j=0;j<a2;++j)

      for(i=j+1;i<a2;++i)

        if(B[j]>B[i]){

               k=B[i];

               B[i]=B[j];

               B[j]=k;

            }

    finish=clock();

    for(i=0;i<a2;++i)printf("%d\t",B[i]);

    printf("\n****time**%d\n",finish-start);

    system("pause");

    //直接插入排序

    start=clock();

    for(i=1;i<a3;++i){

            k=C[i];

            for(j=0;j<i;++j)

               if(k<C[j]){

                   int s=i;

                   while(j<s){

                       C[s]=C[s-1];

                       --s; }

               break;

             }

             C[j]=k;      

    }

    finish=clock();

    for(i=0;i<a3;++i)printf("%d\t",C[i]);

    printf("\n****time**%d\n",finish-start);

    system("pause");

    return 0;

}

程序计算时间问题  
         int   i,a;  
          int   start,end;  
          start   =   clock();  
          for(i=0;i<0x8000000;i++)  
                      a   =   0;  
          end   =   clock();  
          printf("Time   =   %d\n",(end   -   start));  

  1. 1.     注意,时间的数据类型是%d,而不是%f
  2. 2.     2递归调用的不熟练使用。进行快速排序时,不能快速想到递归调用的使用方法,以后应当多加练习。 
  3. 3.     对文件的操作不熟练,对字符串的操作不熟练。

 

插入排序

void InsertSort(int B[],int length){

           int i,j;

           for(i=2;i<length+1;i++){

                     B[0]=B[i];

                     for(j=i-1;B[j]>B[0];j--)

                                B[j+1]=B[j];               

                     B[j+1]=B[0];

           }

}。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

 

                     B[j+1]=B[0];

           }

}

++++++++++++

void QuickSort(int A[],int low,int high){

           int key,i,j;

           i=low;

           j=high;

           key=A[low];

           while(i<j){

                     while(i<j && A[j]>=key)

                                j--;

                     A[i]=A[j];

                     while(i<j && A[i]<=key)

                                i++;

                     A[j]=A[i];

           }

           A[i]=key;

           if(low<i-1)

                     QuickSort(A,low,i-1);

           if(high>i+1)

                     QuickSort(A,i+1,high);

 

}

 

 

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。


第一题:

#include<stdio.h>

#include<time.h>

#include<stdlib.h>

#define N 1000

#define m 300

#define n 400

#define o N-m-n

void main()

{

           clock_t t1,t2;  

           FILE *fp;

           fp=fopen("D:/intfile.dat","wb");

           srand((unsigned)time(NULL));

           int i,j,temp,lap,timeA,timeB,timeC;

           for(i=0;i<N;i++)//读入1000个整数到文件intfile.dat

           {

                     temp=rand();

                     if(fwrite(&temp,sizeof(int),1,fp)!=1)

                     {

                                printf("file write error!\n");

                                break;

                     }

           }

           fclose(fp);

           fp=fopen("D:/intfile.dat","rb");

           int file[N];

           for(i=0;i<N;i++)//将文件intfile.dat中的1000个整数读入数组file[] 

           {

                     if(fread(&file[i],sizeof(int),1,fp)!=1)

                     {

                                printf("file read error!\n");

                                break;

                     }

           }

           fclose(fp);

           int A[m],B[n],C[o];//file[]中将相应的数据放入数组A,B,C

           for(i=0;i<m;i++)

           {

                     A[i]=file[i];

           }

           for(i=0;i<n;i++)

           {

                     B[i]=file[m+i];

           }

           for(i=0;i<o;i++)

           {

                     C[i]=file[m+n+i];

           }

           //.................................................

    t1=clock();//冒泡排序数组A

           for(i=0;i<m-1;i++)

           {

                     for(j=1;j<=m-1-i;j++)

                     {

                                if(A[j]<A[j-1])

                                {

                                          temp=A[j-1];

                                          A[j-1]=A[j];

                                          A[j]=temp;

                                }

                     }

           }

           t2=clock();

           timeA=t2-t1;

           //...............................................

           t1=clock();//简单排序数组B

    for(i=0;i<n-1;i++)

           {

                     temp=B[0];

                     lap=0;

                     for(j=0;j<=n-i-1;j++)

                     {

                                if(B[j]>temp)

                                {

                                          temp=B[j];

                                          lap=j;

                                }

                     }

                     if((n-i-1)!=lap)

                     {

                                temp=B[n-i-1];

                         B[n-i-1]=B[lap];

                                B[lap]=temp;

                     }

           }

    t2=clock();

           timeB=t2-t1;

 

//.........................................  

           t1=clock();//直接插入排序数组C

    int D[o];

           D[o-1]=C[0];

           for(i=0;i<o-1;i++)

           {

                     D[i]=0;

           }

           for(i=1;i<o;i++)

           {

                     j=o-1;

                     while(D[j]>C[i])

                     {

                                j--;

                     }

                     temp=o-i;

                     while((temp-1)!=j)

                     {

                                D[temp-1]=D[temp];

                                temp++;

                     }

                     D[j]=C[i];

           }

           for(i=0;i<o;i++)

           {

                     C[i]=D[i];

           }

           t2=clock();

           timeC=t2-t1;

           //................................................    printf("数组A:\n");//打印数组A,B,C和排序所用时间

           j=0;

           for(i=0;i<m;i++)

           {

                     printf("%d  ",A[i]);

                     j++;

                     if(j==10)

                     {

                                printf("\n");

                                j=0;

                     }

           }

           printf("\n");

           printf("冒泡法排序时间:%d\n",timeA);

    printf("\n");

    printf("数组B:\n");

           j=0;

           for(i=0;i<n;i++)

           {

                     printf("%d  ",B[i]);

                     j++;

                     if(j==10)

                     {

                                printf("\n");

                                j=0;

                     }

           }

    printf("\n");

           printf("简单选择排序时间:%d\n",timeB);

    printf("\n");

           printf("数组C:\n");

           j=0;

           for(i=0;i<o;i++)

           {

                     printf("%d  ",C[i]);

                     j++;

                     if(j==10)

                     {

                                printf("\n");

                                j=0;

                     }

           }

           printf("\n");

           printf("直接插入排序时间:%d\n",timeC);

    printf("\n");

}

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。第二题:

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

#define N 10000

int paixu(int A[N],int low,int high)//快速排序函数

{

           int temp;

           temp=A[low];

           while(high>low)

           {

                     while((A[high]>=temp)&&(high>low))

                     {

                                high--;

                     }

                     A[low]=A[high];

                     while((A[low]<=temp)&&(high>low))

                     {

                                low++;

                     }

                     A[high]=A[low];

           }

           A[low]=temp;

           return low;

}

void dj(int A[N],int low,int high)//递归函数

{

           int lap;

           if(low<high)

           {

                     lap=paixu(A,low,high);

                     if(lap!=low)

                     {

                                dj(A,low,lap-1);

                     }

                     if(lap!=high)

                     {

                                dj(A,lap+1,high); 

                     }

           }

}

void main()//主函数,排序,显示

{

    clock_t t1,t2;

           srand((unsigned)time(NULL));

           int A[N];

           int i,j;

           j=0;

           for(i=0;i<N;i++)

           {

                     A[i]=rand();

           }

           for(i=0;i<N;i++)

           {

                     printf("%d ",A[i]);j++;

                     if(j==10)

                     {

                                printf("\n");

                                j=0;

                     }

           }

           printf("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"); 

           t1=clock();

           dj(A,0,N-1);

printf("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");

           t2=clock();

           for(i=0,j=0;i<N;i++)

           {

                     printf("%d ",A[i]);

                     j++;

                     if(j==10)

                     {

                                printf("\n");

                                j=0;

                     }

           }

           printf("\n花费时间为:%d\n",t2-t1);   

}

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

第三题:

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#define N 5

typedef struct project

{

           int English;

           int Physics;

           int Chinese;

}scores;

typedef struct students

{

           char num[9];

           char name[20];

           char sex;

           scores score;

}student;

float average(student *p)

{

return(((*p).score.English+(*p).score.Chinese+(*p).score.Physics)/3*1.0);

}

int main()

{

           FILE *fp;

           student dj[N],temp;

           int i,j,k;

           i=N;

           printf("一共有%d个学生,输入各个学生信息:\n",i);

for(i=0;i<N;i++){

printf("请输入第%d个学生的信息(用空格隔开):\n",i+1);

           scanf("%s %s %c %d %d %d",dj[i].num,dj[i].name,&dj[i].sex,&dj[i].score.English,&dj[i].score.Chinese,&dj[i].score.Physics);

           getchar();

           } if((fp=fopen("D:/studinfo.dat","wb"))==NULL){

                     printf("file open error!\n");

           }

           for(i=0;i<N;i++)//将学生信息写入文件studinfo.dat

           {

                     if((fwrite(&dj[i],sizeof(struct students),1,fp))!=1){

                                printf("file write error!\n");

                                break;

                     }

           }

           fclose(fp);

    if((fp=fopen("D:/studinfo.dat","rb"))==NULL)

           {

                     printf("file open error!\n");

           }

           student wd[N];

           for(i=0;i<N;i++)//将学生信息从文件studinfo.dat读入wd[N]

{

if((fread(&wd[i],sizeof(struct students),1,fp))!=1){

printf("file read error!\n");

break;

}

}

    fclose(fp);

           char redo;

           redo='y';

           while(redo=='y')

           {

                     printf("您想按什么标准排序:(1学号 2姓名 3平均分)\n");

        scanf("%d",&k);

                     getchar();

        for(i=0;i<N-1;i++)//用冒泡法对不同要求标准排序

                     {

                         for(j=1;j<=N-1-i;j++)

                                {

                                          if(k==1)

                                          {

                                          if(strcmp(wd[j].num,wd[j-1].num)<0) {                                    temp=wd[j-1];                                       wd[j-1]=wd[j];

wd[j]=temp;

}

                                          }

                else if(k==2)

                                          {

                                                     if(strcmp(wd[j].name,wd[j-1].name)<0)

                                                     {

                                                  temp=wd[j-1];

                                                         wd[j-1]=wd[j];

                                                         wd[j]=temp;

                                                     }

                                          }

                                          else

                                          {

                                                     if(average(&wd[j])<average(&wd[j-1]))

                                                     {

                                                               temp=wd[j-1];

                                                         wd[j-1]=wd[j];

                                                         wd[j]=temp;

                                                     }

                                          }

                                }

                     }

            if(k==1)//输出排序情况

                     {

                          printf("\n\n\n按学号排序如下:\n");

                          for(i=0;i<N;i++)

                                {

            printf("%-10s%-15s %c%4d%4d%4d\n",wd[i].num,wd[i].name,wd[i].sex,wd[i].score.English,wd[i].score.Chinese,wd[i].score.Physics);

                                }

                     }

        else if(k==2)

                     {

                         printf("\n\n\n按姓名排序如下:\n");

                          for(i=0;i<N;i++)

                                {

                printf("%-10s%-15s %c%4d%4d%4d\n",wd[i].num,wd[i].name,wd[i].sex,wd[i].score.English,wd[i].score.Chinese,wd[i].score.Physics);

                                }

                     }

               else

                     {

                          float m,n,o;

                          m=n=o=0.0;

                          for(i=0;i<N;i++)

                                {

                                   m=m+wd[i].score.English*1.0;

                                    n=n+wd[i].score.Chinese*1.0;

                                    o=o+wd[i].score.Physics*1.0;

                                }

                          printf("\n\n按平均成绩排序如下:\n");

            for(i=0;i<N;i++)

                                {

                printf("%-10s%-15s %c%4d%4d%4d  该生平均成绩为:%4.1f\n",wd[i].num,wd[i].name,wd[i].sex,wd[i].score.English,wd[i].score.Chinese,wd[i].score.Physics,i+1,average(&wd[i]));

                                }

                          printf("每门课程平均成绩: \nEnglish %4.1f\nChinese %4.1f\nPhysics %4.1f\n",m/N*1.0,n/N*1.0,o/N*1.0);

                     }

                     printf("是否根据其他标准排序?(y/n):\n");

                     scanf("%c",&redo);

               getchar();

           }

           return 0;

}

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。选做题1:

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

#define N 1000

void sort(int A[N+1],int s,int m)


{

           int j,rc;

           rc=A[s];

           for(j=2*s;j<=m;j*=2)

           {

                     if(A[j]<A[j+1]&&(j+1)<=m)

                     {

                                j++;

                     }

                     if(rc>A[j])

                     {

                                break;

                     }

                     A[s]=A[j];

                     s=j;

           }

           A[s]=rc;

}

void main()

{

           srand((unsigned)time(NULL));

           int i,j,m,temp;

           int A[N+1];

           A[0]=N;

           for(i=1;i<=N;i++)

           {

                     A[i]=rand();

           }

           for(i=N/2;i>=1;i--)//建立大顶堆

           {

                     sort(A,i,N);

           }

           for(m=N;m>=3;m--)//大顶堆排序

           {

                     temp=A[m];

                     A[m]=A[1];

                     A[1]=temp;

                     sort(A,1,m-1);

           }

           temp=A[1];//因为是大顶堆,所以最后的A[1]大于A[2],交换它们

           A[1]=A[2];

           A[2]=temp;

    j=0;//输出排序结果

           for(i=1;i<=N;i++)

           {

                     j++;

        printf("%7d",A[i]);

                     if(j==10)

                     {

                                printf("\n");

                                j=0;

                     }

           }

}

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

选做题2

与选做题1同理,代码略。

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

选做题3:

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

#define N 10000

int writefile()//将随机数据写入文件intfile.dat

{

           int A[N];

           srand((unsigned)time(NULL));

           int i;

           for(i=0;i<N;i++)

           {

                     A[i]=rand();

           }

           FILE *fp;

           fp=fopen("D:/intfile.dat","wb");

           for(i=0;i<N;i++)

           {

                     if(fwrite(&A[i],sizeof(int),1,fp)!=1)

                     {

                                printf("file write error!\n");

                                fclose(fp);

                                return 0;

                     }

           }

           fclose(fp);

           return 1;

}

void djsort(int A[],int B[],int i,int m,int n)//数组A[]已经有一定排序,将A[]完全排序,排序结果给数组B[]

{

           int j,k;

           j=m+1;

           for(k=i;(i<=m)&&(j<=n);k++)

           {

                     if(A[i]>A[j])

                     {

                                B[k]=A[j++];

                      }

                     else

                     {

                                B[k]=A[i++];

                     }

           }

           if(i<=m)

           {

                     for(;i<=m;i++)

                     {

                                B[k++]=A[i];

                     }

           }

           if(j<=n)

           {

                     for(;j<=n;j++)

                     {

                                B[k++]=A[j];

                     }

           }

}

void bestsort(int A[],int B[],int m,int n)//A[]排序,结果给B[]

{

           int h;

           int C[N];

           if(m==n)                             

           {                                                        

                     B[n]=A[n]; //这个赋值比较有意思,精华啊,这是递归的难点                                                                         

           }                                                          

           else                                         

           {

                     h=(n+m)/2;

                     bestsort(A,C,m,h);


                     bestsort(A,C,h+1,n);

                     djsort(C,B,m,h,n);

           }

}         

 

 

int main()

{

           int j=0;

           if(writefile()==0) //将数据写入文件intfile.dat

           {

                     return 0;

           }

           FILE *fp;

           fp=fopen("D:/intfile.dat","rb");

           int i,A[N],final[N];

           for(i=0;i<N;i++)//从文件intfile.dat中读出数据给数组A[]

           {

                     if(fread(&A[i],sizeof(int),1,fp)!=1)

                     {

                                printf("file read error!\n");

                                fclose(fp);

                                return 0;

                     }

           }

 

    bestsort(A,final,0,N-1);//归并排序数组A[]

           for(i=0;i<N;i++)//输出排序结果

           {

                     printf("%7d",final[i]);

                     j++;

                     if(j==10)

                     {

                                printf("\n");

                                j=0;

                     }

           }  

    return 0;

}

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

选做题4

利用选做题3djsort()函数和bestsort()函数就可以做出,略。


 

          

 

 

 

 

 

 

栈和队列

#include<stdio.h>

#include<stdlib.h>

#include<stack>

using namespace std;

stack<int> Houzhui;

/*

a=Houzhui.top();只有数字,不弹出

Houzhui.pop();只弹出,没有数字

Houzhui.push(a);压入

*/

//判断某字符是否为数字

int IsNum(char a){

    if((a-'0'>=0)&&(a-'0'<=9))return 1;

    return 0;

}

//判断输入是否结束

int IsEnd(char a){

    if(a=='+'||a=='-'||a=='*'||a=='/'||IsNum(a)||a==' ')return 0;

    return 1;

}

//将字符转换为数字

int Num(char ch){

    return (ch-'0');

}

//计算部分

int Computer(int a,int b,char ch){

    if(ch=='+')return a+b;

    else if(ch=='-')return a-b;

    else if(ch=='*')return a*b;

    else return a/b;

}

int main()

{

    int a,b,i;

    char CH[50],ch;

    printf("请输入一个后缀表达式:\n");

    gets(CH);

    for(i=0,a=0;CH[i]!='\0';++i){

       ch=CH[i];

       if(!IsEnd(ch)){

           if(IsNum(ch)){

                a=10*a+Num(ch);    //不是a+=

                if(CH[i+1]==' '){

                    Houzhui.push(a);

                    a=0;

                }

           }

           else if(ch=='+'||ch=='-'||ch=='*'||ch=='/'){

                b=Houzhui.top();

                Houzhui.pop();

                a=Houzhui.top();

                Houzhui.pop();

                a=Computer(a,b,ch);

                Houzhui.push(a);

                a=0;

           }

       }

    }

    a=Houzhui.top();

    printf("结果为:%d\n",a);

    printf("over\n");

    system("pause");

    return 0;

}******************自己定义*************

#include<stdio.h>

#include<stdlib.h>

#include<malloc.h>

#define SIZE 50

#define RESIZE 10

typedef struct{

        char *base;

        char *top;

        int stacksize;

       }SqStack;

struct List{

       char date;

       struct List*p;

       }*q,Head;

int main()

{

    SqStack S;

    char c;

    printf("请输入一串表达式,\n此程序帮助你表达式中开闭括号是否出现配对:\n停止时请输入“#”\n");

    scanf("%c",&c);

    if(c!='#'){

        Head.p=(List*)malloc(sizeof(List));

        if(!Head.p)exit(0);

        }

    q=Head.p;

    Head.p->date=c;

    for(scanf("%c",&c);c!='#';q=q->p){

        q->p=(List*)malloc(sizeof(List));

        q->p->date=c;

        scanf("%c",&c);

        }

    q->p=0;//此句一定不能忘了!末指针指向"0"!!!

    for(q=Head.p;q->p!=0;q=q->p)

        printf("%c",q->date);

        printf("%c\n",q->date);

    S.top=S.base=(char*)malloc(SIZE*sizeof(char)); 

    for(q=Head.p;q->p!=0;q=q->p)

        if(q->date=='{'||q->date=='}'||q->date==']'||q->date=='('||q->date==')'||q->date=='['){

           *S.top=q->date;

           S.top++;        

           q=q->p;//注意啦!此句一定要加上,因为,若break了,便没有 这步了!!

           break;

           }

    for(;q->p!=0;q=q->p)

        if(q->date=='{'||q->date=='}'||q->date==']'||q->date=='('||q->date==')'||q->date=='['){

            if(q->date==')'&&*(S.top-1)=='('||q->date=='}'&&*(S.top-1)=='{'||q->date==']'&&*(S.top-1)=='[')

                S.top--;       

            else{

                *S.top=q->date;

                S.top++;

                }

            }

    if(q->date==')'&&*(S.top-1)=='('||q->date=='}'&&*(S.top-1)=='{'||q->date==']'&&*(S.top-1)=='[')

               S.top--;    

    if(S.base==S.top)

      printf("yes\n");

    else

      printf("no\n");

    system("pause");

    return 0;

}

 

**********************************************************************************************

#include<stdio.h>

#include<stdlib.h>

#include<stack>

using namespace std;

stack<char> S;

int IsK(char c){                      //判断是否是括号,若是,返回1

    if(c=='{'||c=='}'||c==']'||c=='('||c==')'||c=='[')

       return 1;

    return 0;

}

int IsS(char c1,char c2){              //判断括号是否匹配,若匹配,返回1

    if((c1=='{'&&c2=='}')||(c1=='['&&c2==']')||(c1=='('&&c2==')'))return 1;

    return 0;

}

int main()

{

    int i;char c,a,ch[1000];

    printf("请输入一串表达式,\n此程序帮助你表达式中开闭括号是否出现配对:\n");

    gets(ch);

    for(i=0;ch[i]!='\0';i++){

         c=ch[i];

         if(IsK(c)){

            if(!S.empty()){

                a=S.top();

                if(IsS(a,c)){S.pop();printf("pop----%c%c\n",a,c);}

                else {S.push(c);printf("push----%c\n",c);}

            }

            else {S.push(c);printf("waipush----%c\n",c);}

         }

    }

    if(S.empty())  printf("yes\n");

    else  printf("no\n");

system("pause");return 0;}

***********************************************

图和遍历

#include<stdio.h>

#include<stdlib.h>

#define GraphType int

#define MAX 100

//定义图类型   

//邻接矩阵存储

typedef struct {

        GraphType vexs[MAX];

        int a[MAX][MAX];

        int vexnum,arcnum;    //顶点数和边数

        }Graph1;

//邻接表存储

typedef struct ArcNode{

        int adjvex;

        struct ArcNode *next;

        }ArcNode;

typedef struct VexType{

        GraphType date;

        ArcNode *first;

        }VexType;

typedef struct {

        VexType vex[MAX];

        int vexnum,arcnum;    //顶点数和边数

        }Graph2;

//==============================================    

int CreatGraph1(Graph1 &G){

    int i,j,m,n;

    printf("请输入各个顶点的值\n");

    for(i=0;i<G.vexnum;++i)scanf("%d",&G.vexs[i]);

    for(i=0;i<G.vexnum;++i)

        for(j=0;j<G.vexnum;++j)G.a[i][j]=0;

    printf("请输入边,如“1 2”\n");

    for(i=0;i<G.arcnum;++i){

        scanf("%d%d",&m,&n);

        G.a[m-1][n-1]=1;

        G.a[n-1][m-1]=1;

    }

}

int CreatGraph2(Graph2 &G){

    int i,m,n;

    printf("请输入各个顶点的值\n");

    for(i=0;i<G.vexnum;++i){

        scanf("%d",&G.vex[i].date);

        G.vex[i].first=NULL;

    }

    printf("请输入边,如“1 2”\n");

    for(i=0;i<G.arcnum;++i){

        scanf("%d%d",&m,&n);

        ArcNode *p;

        p=G.vex[m-1].first;

        G.vex[m-1].first=(ArcNode*)malloc(sizeof(ArcNode));

        G.vex[m-1].first->adjvex=n;

        G.vex[m-1].first->next=p;

    }

}  

int visit[MAX];

//==============================================

int DFS1(Graph1 G,int i){

    int k;

    visit[i]=1;

    printf("%d  ",G.vexs[i]);

    for(k=0;k<G.vexnum;++k)

        if(G.a[i][k]==1&&visit[k]==0)DFS1(G,k);

    return 0;

}                              

int DFSGraph1(Graph1 G){

    int i;

    for(i=0;i<G.vexnum;++i)visit[i]=0;

    for(i=0;i<G.vexnum;++i)

        if(!visit[i])DFS1(G,i);

    return 0;

}

//==============================================

int BFSGraph1(Graph1 G){

    int i,j,V[G.vexnum],k1,k2;

    for(i=0;i<G.vexnum;++i)visit[i]=0;

    for(i=j=k1=k2=0;i<G.vexnum;++i)

         if(!visit[i]){

             printf("****\n");

             V[k2]=i;++k2;

             while(k1!=k2){

                   visit[V[k1]]=1;

                   printf("%d  ",G.vexs[V[k1]]);

                   for(j=0;j<G.vexnum;++j)

                       if(G.a[V[k1]][j]==1&&visit[j]==0){V[k2]=j;++k2;}

                   ++k1;

             }

         }

    return 0;

}

//==============================================

int DFS2(Graph2 G,int i){

    ArcNode *p,*q;

    q=p=G.vex[i-1].first;

    visit[i]=1;

    printf("%d  ",G.vex[i-1].date);

    for(;q!=NULL;q=q->next)

        for(p=q;p!=NULL&&visit[p->adjvex]==0;p=G.vex[p->adjvex-1].first)//理解此处p=q的作用!!

            DFS2(G,p->adjvex);

}

int DFSGraph2(Graph2 G){

    int i;

    for(i=1;i<=G.vexnum;++i)visit[i]=0;

    for(i=1;i<=G.vexnum;++i)

         if(!visit[i])DFS2(G,i); 

    return 0;

}

//==============================================

int BFSGraph2(Graph2 G){

    int i,j,V[G.vexnum],k1,k2;

    ArcNode *p;

    for(i=0;i<G.vexnum;++i)visit[i]=0;

    for(i=j=k1=k2=0;i<G.vexnum;++i)

          if(!visit[i]){

             V[k2]=i;++k2;

             while(k1!=k2){

                   visit[V[k1]]=1;

                   p=G.vex[V[k1]].first;

                   printf("%d  ",G.vex[V[k1]].date);

                   for(;p!=NULL;p=p->next)

                      if(visit[p->adjvex-1]==0){V[k2]=p->adjvex-1;++k2;}

                      //此处要注意!! p->adjvex-1  处理数组的0元素是否存储数据

                   ++k1;

             }

          }

    return 0;

}

          

int main()

{

    int m,n,k;

    printf("请输入图的顶点数,边数\n");

    scanf("%d%d",&m,&n);

    printf("请选择图的存储方式\n1-邻接矩阵存储\n2-邻接表存储\n");

    scanf("%d",&k);

    if(k==1){

             Graph1 Graph;

             Graph.vexnum=m;

             Graph.arcnum=n;

             CreatGraph1(Graph);

             printf("深度优先遍历序列为:\n");

             DFSGraph1(Graph);

             printf("\n广度优先遍历序列为:\n");

             BFSGraph1(Graph);

             }

    else{

             Graph2 Graph;

             Graph.vexnum=m;

             Graph.arcnum=n;

             CreatGraph2(Graph);

             printf("深度优先遍历序列为:\n");

             DFSGraph2(Graph);

             printf("\n广度优先遍历序列为:\n");

             BFSGraph2(Graph);

             }

    system("pause");

}

   

     **********************************************************************************************

//深度遍历图  邻接矩阵

#include<stdio.h>

#include<stdlib.h>

#define Max 100

typedef struct Graph{

        int v[Max];

        int arcs[Max][Max];

        int vexnum,arcnum;

        }Graph;

int CreatGraph(Graph &G){

    int m,n,i,j;

    printf("请输入节点数和边数:");

    scanf("%d%d",&G.vexnum,&G.arcnum);

    for(i=1;i<=G.vexnum;++i)

         for(j=1;j<=G.vexnum;++j)G.arcs[i][j]=0;

    printf("请输入各个边所依附的顶点;");

    for(i=1;i<=G.arcnum;++i){

         scanf("%d%d",&m,&n);

         G.arcs[m][n]=G.arcs[n][m]=1;

    }

    return 0;

}

int visited[Max];

int DFS(Graph G,int v){

    int i;

    visited[v]=1;

    printf("%d  ",G.v[v]);

    for(i=1;i<=G.vexnum;++i)

          if(!visited[i]&&G.arcs[v][i])DFS(G,i);

    return 0;

}

int DFST(Graph G){

    int i;

    for(i=1;i<=G.vexnum;++i)

      if(!visited[i])DFS(G,i);

    return 0;

}

int main(){

    int i,j,k;Graph G;

    CreatGraph(G); 

    for(i=1;i<Max;++i){visited[i]=0;G.v[i]=i;}

    DFST(G);

    system("pause");

    return 0;

}

*********************************************************************************************

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

最小生成树

#include<stdio.h>

#include<stdlib.h>

#define GraphType int

#define MAX 100

typedef struct Visit{

        int m,n;//此边连接的两个顶点序号

        int weight;//此边的权值

        }Visit;

Visit v[MAX];

int Q;

int read[MAX];//为顶点设置的变量

//邻接表存储

typedef struct ArcNode{

        int adjvex;       //节点序号

        int weight;

        struct ArcNode *next;

        }ArcNode;

typedef struct VexType{

        GraphType date;   //顶点存储的数据

        ArcNode *first;

        }VexType;

typedef struct {

        VexType vex[MAX];

        int vexnum,arcnum;  //顶点数和边数

        }Graph2;

//==============================================

int CreatGraph2(Graph2 &G){

    int i,m,n,k;

    for(i=0;i<G.vexnum;++i)G.vex[i].first=NULL;

    printf("请输入边以及其权值,如“1 2 5”\n");

    for(i=0;i<G.arcnum;++i){

        scanf("%d%d%d",&m,&n,&k);

        ArcNode *p;

        p=G.vex[m-1].first;

        v[0].m=v[0].m+1;

        v[i+1].m=m;

        G.vex[m-1].first=(ArcNode*)malloc(sizeof(ArcNode));

        G.vex[m-1].first->adjvex=v[i+1].n=n;

        G.vex[m-1].first->weight=v[i+1].weight=k;

        G.vex[m-1].first->next=p;

    }

    return 0;

}

//==============================================

int Sort(Visit v[]){

    int i,j;

    Visit k;

    for(i=1;i<=v[0].m;++i)

       for(j=i+1;j<=v[0].m;++j)

          if(v[i].weight>v[j].weight){

                k=v[i];

                v[i]=v[j];

                v[j]=k;

          }

    return 0;

}

int Compare(int m,int n,int weight,int read[]){           //判断是否成圈

    int i;

    for(i=1;i<MAX;++i){

            if(read[i]&&m==i&&!read[n]){

                printf("顶点:%d,%d  权值:%d\n",i,n,weight);

                Q+=weight;

                return n;

            }

            else if(read[i]&&n==i&&!read[m]){

                printf("顶点:%d,%d  权值:%d\n",i,m,weight);

                Q+=weight;

                return m;

            }

            else;

        }

    return 0;

}      

//==============================================           

int MiniSpanTree(Graph2 &G){

    int i,j,k,x,l,m,n,count;

    Q=count=0;

    read[1]=1;

for(i=1;i<G.vexnum;++i){

//边的个数为为点的个数减一

        for(j=1;j<=G.arcnum;++j){   //遍历所有的边

             if(v[j].weight){

                 x=Compare(v[j].m,v[j].n,v[j].weight,read);

                 if(x){

                    read[x]=1;  //此点已经加入

                    v[j].weight=-1; //此边已经加入

                    break;

                 }//if

             }//if

        }//for

    }//for

    return 0;

}                    

int main()

{

    int m,n,k,i;

    v[0].m=0;          //计数作用

    printf("请输入图的顶点数,边数\n");

    scanf("%d%d",&m,&n); 

    for(i=1;i<MAX;++i)read[i]=0;

    Graph2 Graph;

    Graph.vexnum=m;

    Graph.arcnum=n;

    CreatGraph2(Graph);

    Sort(v);

    MiniSpanTree(Graph);

    printf("总的权值为:%d\n",Q);

    system("pause");

    return 0;

}

*************************************************************************************

#include<stdio.h>

#include<stdlib.h>

#define GraphType int

#define MAX 100

typedef struct Visit{

        int m,n;//此边连接的两个顶点序号

        int weight;//此边的权值

        }Visit;

Visit v[MAX];

int Q;

int read[MAX];//为顶点设置的变量

//邻接表存储

typedef struct ArcNode{

        int adjvex;       //节点序号

        int weight;

        struct ArcNode *next;

        }ArcNode;

typedef struct VexType{

        GraphType date;   //顶点存储的数据

        ArcNode *first;

        }VexType;

typedef struct {

        VexType vex[MAX];

        int vexnum,arcnum;  //顶点数和边数

        }Graph2;

//==============================================

int CreatGraph2(Graph2 &G){

    int i,m,n,k;

    for(i=0;i<G.vexnum;++i)G.vex[i].first=NULL;

    printf("请输入边以及其权值,如“1 2 5”\n");

    for(i=0;i<G.arcnum;++i){

        scanf("%d%d%d",&m,&n,&k);

        ArcNode *p;

        p=G.vex[m-1].first;

        v[0].m=v[0].m+1;

        v[i+1].m=m;

        G.vex[m-1].first=(ArcNode*)malloc(sizeof(ArcNode));

        G.vex[m-1].first->adjvex=v[i+1].n=n;

        G.vex[m-1].first->weight=v[i+1].weight=k;

        G.vex[m-1].first->next=p;

    }

    return 0;

}

//==============================================

int Sort(Visit v[]){

    int i,j;

    Visit k;

    for(i=1;i<=v[0].m;++i)

       for(j=i+1;j<=v[0].m;++j)

          if(v[i].weight>v[j].weight){

                k=v[i];

                v[i]=v[j];

                v[j]=k;

          }

    return 0;

}

//==============================================           

int MiniSpanTree(Graph2 &G){

    int i,j,k,l,m,n,count;

    Q=count=0;

    for(i=1;;++i){

        m=v[i].m;n=v[i].n;

        if(read[n]!=read[m]){

      


     k=read[n];l=read[m];

            printf("顶点:%d,%d  权值:%d\n",v[i].m,v[i].n,v[i].weight);

            Q+=v[i].weight;

            count++;

            if(count==G.vexnum-1)return 0;

            v[i].weight=-1;

            if(read[m]<0){ 

                if(read[n]<0)//二者都加入了某个集合

                   for(j=1;j<=G.vexnum;++j)

                       if(read[j]==k)read[j]=read[m];             

                else{  //m加入了,n未加入,则n加入m

                    for(j=1;j<=G.vexnum;++j)

                       if(read[j]==k)read[j]=read[m];

                   }

            }

            else if(read[n]<0){//n加入了,m未加入,m则加入n

                   for(j=1;j<=G.vexnum;++j)

                       if(read[j]==l)read[j]=read[n];

            }

            else //二者都未曾加入过,在此read值相同表示在同一集合,负号表示加入了某个集合

                 read[m]=read[n]=-1*read[n];

        }

    }

    return 0;

}                    

int main()

{

    int m,n,k,i;

    v[0].m=0;                        //计数作用

    printf("请输入图的顶点数,边数\n");

    scanf("%d%d",&m,&n); 

    for(i=1;i<=m;++i)read[i]=i;

    Graph2 Graph;

    Graph.vexnum=m;

    Graph.arcnum=n;

    CreatGraph2(Graph);

    Sort(v);

    MiniSpanTree(Graph);

    printf("总的权值为:%d\n",Q);

    system("pause");

    return 0;

}


 

最短路径

#include<stdio.h>

#include<stdlib.h>

#define GraphType int

#define MAX 100 

int D[MAX];

int P[MAX][MAX];

int final[MAX];

int V[MAX],v[MAX];

int v1=0;         //邻接矩阵存储

typedef struct {

        int vex[MAX];

        int a[MAX][MAX];

        int vexnum,arcnum;  //顶点数和边数

        }Graph1;

//==============================================      

int CreatGraph1(Graph1 &G){

    int i,j,m,n,k;

    for(i=0;i<G.vexnum;++i)G.vex[i]=i;

    for(i=0;i<G.vexnum;++i)

        for(j=0;j<=G.vexnum;++j)G.a[i][j]=MAX;

    printf("请输入边及其权值,如“1 2 5”\n");

    for(i=0;i<G.arcnum;++i){

        scanf("%d%d%d",&m,&n,&k);

        G.a[m][n]=k;

    }

}

//==============================================

int ShortPath(Graph1 G){

    int i,v0,v,w,min,j;

    printf("请输入起点");

    scanf("%d",&v0);

    for(v=0;v<G.vexnum;++v){

         final[v]=0;D[v]=G.a[v0][v];

         for(w=0;w<G.vexnum;++w)P[v][w]=0;

         if(D[v]<MAX){P[v][v0]=1;P[v][v]=1;}

    }

    D[v0]=0;final[v0]=1;V[v0]=v1;v1++;

    for(i=1;i<G.vexnum;++i){

         min=MAX;

         for(w=0;w<G.vexnum;++w)

             if(!final[w])

                 if(D[w]<min){v=w;min=D[w];}

         final[v]=1;V[v]=v1;v1++;

         for(w=0;w<G.vexnum;++w)

             if(!final[w]&&(min+G.a[v][w]<D[w])){

                  D[w]=min+G.a[v][w];

                  for(j=0;j<G.vexnum;++j)P[w][j]=P[v][j];P[w][w]=1;

             }

    }

}   

//==============================================int main()

{

    int m,n,k,i,j,l,c,a;

    printf("请输入图的顶点数,边数\n");

    scanf("%d%d",&m,&n);

    Graph1 Graph;

    Graph.vexnum=m;

    Graph.arcnum=n;

    for(i=0;i<m;++i)V[i]=0;

    CreatGraph1(Graph);

    ShortPath(Graph);

    for(i=0;i<m;++i){

       k=0;

       for(j=0;j<m;++j)v[j]=MAX;

       for(j=0;j<m;++j)

           if(P[i][j])v[j]=V[j];

       for(a=0;a<m;++a){

           for(j=0,l=v[j],c=j;j<m;++j)

               if(l>v[j]){c=j;l=v[j];}

           if(v[c]!=MAX){printf("V%d",c);v[c]=MAX;k=1;}

       }

       if(k)printf("\n");

    }

    system("pause");

    return 0;

}

posted @ 2013-11-24 11:33  little white  阅读(479)  评论(0编辑  收藏  举报