一个关于用链表读单词排序的问题?

时间:2008-05-21 08:44:56   来源:论坛整理  作者:  编辑:chinaitzhe
下面的这个程序似乎撤底失败了,到处都是错误。
我说下思路,希望有好心人,能够帮我改改,或写一个正确的让我借鉴一下。
谢谢了。

程序是在一个英文的.txt里面读取单词。然后在把这些单词排序后,写入另一个文件。
最好能够把相同的单词剃掉。

还有就是我能够理解的最大只到链表,其它的还没有学呢。希望老师们写的不要太深。
谢谢了。

C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/



#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <time.h>

#include <ctype.h>



#define MAX 300

struct item{

    char word[MAX];

};

 struct node{

    struct item  Item;

    struct node  * next;

    };

 struct list{

     struct node * head;

     struct node * last;

 };

//创建新的项目

void copy_To_item (struct node *ptr1,char * addchar)

{

    strcpy(ptr1->Item.word,addchar);

}



void copy_To_node(struct list *List, struct node *Node)

{

    if(List->head == NULL)

    {

        List->head = Node;

        List->last = List->head;

    }

    else

    {

        List->last->next = Node;

        List->last = List->last->next;

    }

}



struct node * sort(struct node * head)

{

    struct node *ptr1 = head;

    struct node *ptr2 = head->next;

    char temp[MAX];

    while(ptr1!=NULL)

    {

        while(ptr2!=NULL)

        {

            if(strcmp(ptr1->Item.word,ptr2->Item.word) == 1)

            {

                memcpy( temp,           ptr1->Item.word,10);

                memcpy( ptr1->Item.word,ptr2->Item.word,10);

                memcpy( ptr2->Item.word,           temp,10);

            }

            ptr2=ptr2->next;

        }//while ptr2

        ptr1 = ptr1->next;

    }//while ptr

    return head;

}

int main(void)

{



    struct list * List;

    struct node    tp;

    struct node * Node;



    long addnum = 0;

    long sum = 0;//单词的个数

    long over;

    long j=0;//for

    long strat,end;//时间

    long file_max;//目标文件的大小

    char name[20];//文件名称

    char tmp;//tmp = getc(in);

    char add[MAX];//读取的字符,放到这里

    int  space = 0;

    FILE * in, * out;



    //初使化链表

    List = (struct list *) malloc(strlen(add)   sizeof(List->head->next));

    List->head = NULL;

    List->last = NULL;



    strat = clock();

    gets(name);

    if((in = fopen(name,"r")) == NULL)

    {

        fputs("没有打开文件!\n",stdout);

        exit(EXIT_FAILURE);

    }

    if((out = fopen("1234.txt","a ")) == NULL)

    {

        fputs("没有打开文件",stdout);

        exit(EXIT_FAILURE);

    }

      //得到目标文件的大小

    fseek(in,0L,SEEK_END);

    file_max = ftell(in);

    printf("file_max = %d\n",file_max);

    rewind(in);

    //把单词读入数组,剃除空格

    puts("开始读取数据!!");

        while((tmp = getc(in)) != EOF )

        {

            

            //当前读取的字节

            addnum = ftell(in);

            //printf("已经读取的字节  %d      \n",addnum);

            if(!isspace(tmp) && '\n' != tmp)

            {

                add[j] = tmp;

                j  ;

                space = 0;

            }

            if(isspace(tmp) || '\n' == tmp)

            {

/////////////////////////////////////////////////////////////////////////////

                j = 0;

                space  = 1;    

                if(1 == space && addnum != 1)

                {

                    //给链表添加新的项目

                    Node = (struct node *) malloc(strlen(add)   5);

                    if(NULL == Node)

                    {

                        printf("没有可用内存\n");

                        system("pause");

                    }        

                    copy_To_item(Node,add);

                    Node->next = NULL;

                    copy_To_node(List,Node);



                    sum = sum   1;

                    printf(" %d !\n",sum);

                }

            }

        }

    printf("共读取了  %d      个单词!\n",sum);

    printf("addnum = %d\n",addnum);

    puts("开始排序!!!");

    List->head = sort(List->head);



    puts("开始写入文件!!");

    tp = *List->head;

    while(tp.next != NULL)

    {

        fprintf(out,"%s\n",tp.Item.word);

        tp = *tp.next;

    }



    while(List->head != NULL)

    {

        tp = *List->head->next;

        free(List->head);

        *List->head = tp;

    }

    fclose(in);

    fclose(out);

    for(over=0;over<5;over  )

        printf("\a");

    end = clock();

    printf("%d",(end - strat)/CLOCKS_PER_SEC);

    system("pause");

    return 0;

}




网友回复:
C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/





//很久前做的.比你要的多了个查找.

////////////////

//a.txt:

//abs while title name why what how hello direction no ability

/////////////////

#include<stdio.h>

#include<malloc.h>

#include <stdlib.h> 

#include<string.h>

//#include<iostream.h>



#define LEN 20

typedef struct lone{

    char a[20];

    struct lone *next;

}node;



node *read(node *head,int *n)

{

     node *p1,*p2;

     int m=0;     

     FILE *fp;

     if((fp=fopen("a.txt","r"))==NULL)

     {     

         printf("can not open the file\n");

         exit(0); 

     }

     do

     {

         p1=(node *)malloc(sizeof(node));

         fscanf(fp,"%s",&p1->a);

         if(m==0)      

         {

             p2=p1;

             head=p1;

         }

         else

         {

             p2->next=p1;

         }

         p2=p1;

         m  ; 

     }while(!feof(fp));

     *n=m;

     p2->next=NULL;

     fclose(fp);

return head;

}

void sort(node *head,int n)

{

    

    node *ptr1,*ptr2,*temp,*ptr3;    

    ptr3=head;

    while(ptr3!=NULL)

    {

        ptr1=head;

        ptr2=head->next;

        ptr3=ptr3->next;

        while(ptr2!=NULL)

        {

            if(strcmp(ptr1->a,ptr2->a)>0)

            {    

                temp=(node *)malloc(sizeof(node));

                strcpy(temp->a,ptr2->a);

                strcpy(ptr2->a,ptr1->a);

                strcpy(ptr1->a,temp->a);

            }

        ptr1=ptr2;

        ptr2=ptr2->next;    

        }

        

    }

}

void search(node *head)

{

    int i=0,m=0;

    char *b[LEN]={"what","is","you","name"};//LEN你可以自己定义,我这定义的最多是20个单词的,要输入语句的单词就在这里面改

    while(b[i  ]!=NULL)                   //example:*b[LEN]={"I","like","this","GAME","WHAT","you","like"};   

    {

        m  ;

    }

    node *p;

    p=(node *)malloc(sizeof(node));

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

    {     p=head;     

        while( p!=NULL && strcmpi(p->a,b[i])!=0)

        {               

            p=p->next;

        }

        if(p!=0)

        {

            printf("find p->a: %s\n",p->a);

        }

        if(!p)

        {

            printf("error,this word [%s] was not find\n",b[i]);                

        }  

    }

    p=NULL;

}

void main()

{

    node *head=NULL,*p3;

    int n;

    int cnt = 0; //

    head=read(head,&n);

    printf("in file have =%d word\n",n);

    p3=head;



     while(p3 != NULL) //输出读取进来的文件中的单词

     {

        printf("this num %d: %s\n",  cnt,p3->a); 

        p3=p3->next;

     }



    sort(head,n);//排序

    p3=head;

    printf("\n");



    cnt = 0;

    while(p3!=NULL) //输出排序后的链表

    {

        printf("this num %d :%s\n",  cnt,p3->a); 

        p3=p3->next;

    }

    search(head); //查找匹配单词

}



//result:



in file have =11 word

this num 1: abs

this num 2: while

this num 3: title

this num 4: name

this num 5: why

this num 6: what

this num 7: how

this num 8: hello

this num 9: direction

this num 10: no

this num 11: ability



this num 1 :ability

this num 2 :abs

this num 3 :direction

this num 4 :hello

this num 5 :how

this num 6 :name

this num 7 :no

this num 8 :title

this num 9 :what

this num 10 :while

this num 11 :why

find p->a: what

error,this word [is] was not find

error,this word [you] was not find

find p->a: name

Press any key to continue






网友回复:对不起呀! 你的这个不符合我的要求。

文件里的内容是下面这样的:
用你的读取字符串的方法不太合适。
You re going to bndon mejust like thtB I m sorrybut I ve got n importnt job to dobndonvt yNWbebndon oneself to lnNwith bndon eNWeWW I think it s importnt tht ll people hve the bility to redB I gree with youbut tht s esier sid thn donebilityn RgMbMbfto the best of one s bility gYRR How mny pssengers re there bord the shipB SeventysixI thinkbordprep WgfNNgfd WbgfNNbgf re you plnning on studying brodB I d like tobut I m not sure if I ll hve enough moneybrodd RVYWVYW OdWm O I noticed your bsence in clss this morningB I m sorryI oversleptbsencen NWveYQgONNXW I cn t believe the boss ws bsent from tody s meetingB Neither cn I bsent vNWWvONvNXWvNWqvQyv We hve bsolute proof tht you committed the crimeB Tht s bsolutely ridiculousbsolute SvSWvvhQvNSNUOPRbgv This pper bsorbs wter so quicklyB Yesit s gret for clening up spillsbsorbvt TeT vlOhQylb veQTS Why ren t you doing well in the clssB The mteril is so bstrct tht I hve trouble understnding itbstrct bvbmvn XdhibmgOTvt P vXdcSbSin the bstrct bWWtN Lbor is n
bundnt resource hereB One of mny bundnt resourcesI d like to point outbundnt YvEQvinNvv I hte to see the buse of nimlsB It mkes me sickbusen nuYu PO kvt nuYu PO k I relly dislike reding cdemic booksB Tht my be sobut reding them is n importnt wy to expnd your knowledgecdemic fhvfbvfgvtvNREvn YfYe The cdemy is n importnt prt of the eduction systemB I couldn t gree with you morecdemyn xvbfEVERYONES


MONEY BOOK


THIRD EDITION


JORDN E GOODMN


This publiction is designed to provide ccurte nd uthorittive informtion in regrd
to the subject mtter covered It is sold with the understnding tht the publisher is not
engged in rendering legl ccounting or other professionl service If legl dvice or
other expert ssistnce is required the services of competent professionl person
should be sought

Vice President nd Publisher Cynthi igmund
Senior Mnging Editor Jck Kibur
Interior Design The Publishing Services Group
Cover Design Design llince Inc
Cover Photo Doug Finley

by mherst Enterprises Ltd

Published by Derborn Trde Kpln Professionl Compny

ll rights reserved The text of this publiction or ny prt thereof my not be reproduced
in ny mnner whtsoever without written permission from the publisher

Printed in the United Sttes of meric



Librry of Congress CtloginginPubliction Dt

Goodmn Jordn Elliot
Everyones money book Jordn E Goodmn rd ed

p cm
Includes bibliogrphicl references nd index
ISBN
Finnce Personl Investments I Title
HGG
dc
Derborn Trde books re vilble t specil quntity discounts to use s premiums nd
sles promotions or for use in corporte trining progrms For more informtion plese
cll the Specil Sles Mnger t ext or write to Derborn Trde
North Wcker Drive Chicgo IL


Dediction


To my wife Sunne whose unwvering support throughout months of unrelenting
work mde this book possible nd my son Json who lso helped his
dddy complete The Money Book even though it ws hrd for him to understnd
why Dddy ws unvilble to ply with him for so long

cknowledgments


Everyones Money Book would not hve been possible without the generous
contributions nd extremely hrd work of mny tlented people

Foremost mong these contributors re the stff of Derborn Trde who exhibited
incredible tem spirit nd professionlism in mking this book relity
Vice President nd Publisher Cynthi igmund recognied the need to revise nd
updte wht hs become clssic work in the field of personl finnce dding not
only the ltest resources but lso the mny sections on how to mximie the use of
your computer to improve your personl finncil mngement

Senior Mnging Editor Jck Kibur skillfully guided this edition through the
process from originl mnuscript to finl published work

Mny other people t Derborn were enormously importnt in mking the concept
of Everyones Money Book relity Robert Kyle former chirmn of the bord
nd nit Constnt former senior vice president provided unwvering support for
ll phses of the first edition Former president Dennis Blit ws eqully supportive
of the revised nd updted version Pul Mllon sles director enthusisticlly gve
the book his full bcking Todd Snders of the Publishing Services Group produced
mny welldesigned renderings which will help you understnd complex concepts
more clerly Judy Quinnert in mnufcturing coordinted the timely printing nd
binding of the book rt Director Lucy Jenkins contributed her invluble ssistnce
with the color nd design of the dust jcket The stff of the dotted i worked without
complint to typeset this book under extremely tight dedlines nd displyed enormous
flexibility in meeting our schedules I lso pprecite the efforts of Senior Editoril
ssistnt Sndr Thoms nd indexer Shron Johnson

This third edition would not hve been possible without the enormous dediction
intelligence nd hrd work of ustin Lyns who worked for months updting
ll of the resources of the book In prticulr he reserched thousnds of Web
sites to help identify the sites tht would be most useful nd relible for you to use


CKNOWLEDGMENTS

I thnk Money mgine Mnging Editor Frnk Llli ssistnt Mnging
Editor Frnk B Merrick nd ssocite Publisher Betsy Mrtin for their support
nd encourgement of this project including their willingness to llow me to tke
leve of bsence to work on the book

I lso offer my hertfelt grtitude to the mny people who reviewed every word
of Everyones Money Book for ccurcy nd style Elliot R Goodmn professor
emeritus of politicl science t Brown University nd Norm B Goodmn n stute
investor meticulously reviewed the entire book nd suggested hundreds of
helpful improvements s my prents their contribution extended fr beyond the
cll of prentl duty

Ech of the individul chpters ws lso reviewed by highly esteemed expert
in the relevnt field often n uthor of Derborn book on the subject


Lorett Noln certified finncil plnner nd president of Noln ssocites
in Greenwich Connecticut who skillfully offered suggestions on
Chpter Giving Yourself Finncil Checkup

Mrk Skousen editor of the investment newsletter Forecsts Strtegies
uthor of Scrooge Investing nd couthor of High Finnce on Low Budget
thoroughly reviewed Chpter on csh instruments

Gene Wlden uthor of The Best Stocks to Own in meric scrutinied
Chpter on stocks

Stephen Littuer uthor of How to Buy Mutul Funds the Smrt Wy
checked Chpter on mutul funds for ccurcy

Gerld Krefet uthor of the Mking the Most of Your Money Series offered
severl helpful comments on Chpter bout bonds

Willim F Eng the uthor nd interntionl lecturer of technicl nlysis
nd mrket psychology books including Options Trding Strtegies Tht
Work Trding Rules nd mny other books reviewed Chpter on futures
nd options

Brt Sotnick nd Steven R Mlin stff directors of press nd community reltions
for the New York Federl Reserve Bnk who grciously shred their
expertise on Tresury securities nd other csh instruments

Dvid E Crlson mnger of the Deprtment of Finncil nd Sles Prctice
Complince t the Chicgo Bord Options Exchnge who reviewed Chpter
on Futures nd Options

John H Lutley president of the Gold Institute in Wshington DC checked
the ccurcy of the gold section in Chpter nd Steve Bobbitt medi reltions
director of the mericn Numismtic ssocition checked the ccurcy
of the section on numismtic coins rn Murphy of the Pltinum Guild
Interntionl checked the section on Pltinum nd provided the grph show

CKNOWLEDGMENTS

ing the movement of pltinum nd gold prices over the long term Dvid J
Mloney professionl ppriser nd uthor of Mloneys ntiques Collectibles
Resource Directory provided invluble guidnce on the collectibles


把上面的这段不是文章的文章进行排序然后写入一个文件:
写进文件的内容的格式要:
word1
word2
word3
.....
单词的顺序按字母表顺序。。。
希望有高指点。。
网友回复:你意思排好后写入文件的时候还是按原来的段落形式写?

网友回复:不是
一行一个单词就行了。
把文章里的单词按首字母排序,然后写入文件,
单词1
单词2
单词3
单词4
单词5
。。。。。。。。。。
网友回复:
C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/





//ok了

#include<stdio.h>

#include<malloc.h>

#include <stdlib.h> 

#include<string.h>



typedef struct lone{

    char a[40];

    struct lone *next;

}node;



node *read(node *head,int *n) 

{

     node *p1,*p2;

     int m=0;     

     FILE *fp;

     if((fp=fopen("in.txt","r"))==NULL)//从in.txt读入到链表

     {     

         printf("can not open the file\n");

         exit(0); 

     }

     do

     {

         p1 = (node *)malloc(sizeof(node));

      

         fscanf(fp,"%s",&p1->a);

         if(m==0)      

         {

             p2=p1;

             head=p1;

         }

         else

         {

             p2->next=p1;

         }

         p2=p1;

         m  ; 

     }while(!feof(fp));

     *n=m;

     p2->next=NULL;

     fclose(fp);

return head;

}

void sort(node *head,int n)

{

    

    node *ptr1,*ptr2,*temp,*ptr3;    

    ptr3=head;

    while(ptr3!=NULL)

    {

        ptr1=head;

        ptr2=head->next;

        ptr3=ptr3->next;

        while(ptr2!=NULL)

        {

            if(strcmpi(ptr1->a,ptr2->a)>0)

            {    

                temp=(node *)malloc(sizeof(node));

                strcpy(temp->a,ptr2->a);

                strcpy(ptr2->a,ptr1->a);

                strcpy(ptr1->a,temp->a);

            }

        ptr1=ptr2;

        ptr2=ptr2->next;    

        }

        

    }

}



void output(node *head,int n)

{

    node *current;

    current = head;

    FILE *fout;

    if( (fout=fopen("out.txt","w")) == NULL )

    {

        exit(-1);

    }



    while(current->next != NULL)

    {

        

        fprintf(fout,"%s\n",current->a);        

        current = current->next;

    }



    fclose(fout);



}

void main()

{

    node *head=NULL,*p3;

    int n;

    int cnt = 0; 

    head=read(head,&n);

    printf("in file have =%d word\n",n);

    p3=head;



     while(p3->next != NULL) //输出读取进来的文件中的单词

     {

        printf("this num %d: %s\n",  cnt,p3->a); 

        p3=p3->next;

     }



    sort(head,n);//排序

    p3=head;

    printf("\n");



    cnt = 0;

    while(p3->next!=NULL) //输出排序后的链表

    {

        printf("this num %d :%s\n",  cnt,p3->a); 

        p3=p3->next;

    }

    

    output(head,n); //输出到文件

}










网友回复:看来c 的基础函数没有学习好。明明知道有scanf(); 和fscanf();(而且这些函数我都学过了,但是确不知道用) 这样的函数 竟然还自己去实现。 哎!!!

后边学,前边忘!!!
关键字:一个,链表读,单词,排序,问题,

相关文章

文章评论

共有 0 位网友发表了评论 此处只显示部分留言 点击查看完整评论页面