统计Txt中数字个数 并存入链表

/********************************************************************
/*功能:统计txt文件中16进制数字个数。PS最后一个数字后不能有空格,数字之间是空格不是逗号
/*日期:160816
/*作者:
/*结论:
/*******************************************************************/


#include<stdio.h>
#include <stdlib.h> /*含ma l l o c ( ) 的头文件*/

//链表定义
struct Str_LianBiao
    {
       int num;
       struct Str_LianBiao * next;
    };

//链表创建函数声明
struct Str_LianBiao *creat();
void print(struct Str_LianBiao *head);

int main()
{
   

    struct Str_LianBiao *head;
    head=NULL;//创建一个空链表
    struct Str_LianBiao *p1, *p2;
    p1=p2=(struct Str_LianBiao *)malloc(sizeof(struct Str_LianBiao));////利用malloc ( )函数向系统申请分配一个节点
    p1->next=NULL; ///*将新节点的指针置为空*/


    int data2;
    int num=0;
    FILE *fp=fopen("待读取数据.txt","r");
    //FILE *fp=fopen("D:\\待读取数据.txt","r");

    if(!fp)
    {
       printf("Can't open file!\n");
       return -1;
    }

    while(!feof(fp))
    {
        fscanf(fp,"%x", &data2);
        printf("%d ",data2);
        num++;
        
        p1->num=data2; //将数据写入链表中
        if(head==NULL)
        {
          head=p1; //空表,接入表头
        }
        else
        {
         p2->next=p1; //非空表,接入表尾部。
        
        }
         p2=p1;
        p1=(struct Str_LianBiao*)malloc(sizeof(struct Str_LianBiao));/*下一个新节点*/  
    
    }

    free(p1);  //申请到的没录入,所以释放掉    
    p1=NULL;   //使指向空    
    p2->next = NULL; //到表尾了,指向空    
    printf("链表输入结束(END)\n");    

     print(head);/*打印单链表*/  

    printf("\nThe number is: %d ", num);
    fclose(fp);

   /*********************输出打印*************************/
    char ShuChuDaYin[]="Shu Chu is OK!!!!";
    printf("\n%s\n", ShuChuDaYin);
    return 0;
}


void print(struct Str_LianBiao *head)/*出以head为头的链表各节点的值*/  
{  
    struct Str_LianBiao *temp;  
    temp=head;/*取得链表的头指针*/  
 
    printf("\n\n\n链表存入的值为:\n");  
    while(temp!=NULL)/*只要是非空表*/  
    {  
        printf("%6d\n",temp->num);/*输出链表节点的值*/  
        temp=temp->next;/*跟踪链表增长*/  
    }  
    printf("链表打印结束!!");  
}


   

猜你喜欢

转载自blog.csdn.net/shayne_lee/article/details/52225758