69,382
社区成员
发帖
与我相关
我的任务
分享
#include "std.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int len = 0;
struct node
{
char *word;
int count;
struct node *next;
}*head,*p,*q;
struct node* printf_sort(struct node *head)
{
struct node *p1,*p2,*ptemp,*pfinished = NULL;
for (p1 = head; p1->next != pfinished;)
{
for (p2 = p1; p2->next != pfinished;)
{
if (p2->count < p2->next->count)
{
if (p2 == p1)
{
p1 = p2->next;
p2->next = p1->next;
p1->next = p2;
ptemp = p1;
}
else
{
ptemp->next = p2->next;
ptemp = p2->next;
p2->next = ptemp->next;
ptemp->next = p2;
}
}
else
{
ptemp = p2;
p2=p2->next;
}
}
pfinished = p2;
}
}
int main(int argc, char *argv[])
{
int ndisp = 0;
struct timeval starttime, endtime, durtime;
int i = 0;
/* step0: get cmd parameter and check it */
if (argc < 2){
printf("USAGE: wordcount <filename> [Top # of results to display]\n");
exit(0);
}
char *filename = *(argv + 1);
/* step1: prepare work (e.g. open file, load file to memory ...) */
FILE *file;
if ((file = fopen(filename, "r")) == NULL){
printf("cannot open this file\n");
exit(0);
}
printf("wordcount: Running...\n");
gettimeofday(&starttime, 0);
/* step2: do word count */
char ch;
head = NULL;
while ((ch = fgetc(file)) != EOF)
{
while (ch == ' ')
ch = fgetc(file);
if (ch <= 'Z')
ch += 32;
i = 0;
q = (struct node *) malloc(sizeof(struct node));
char temp[20];
while (ch = fgetc(file) != ' ')
{
temp[i] = ch;
i++;
}
int same = 0;
for (p = head; p != NULL; p = p->next)
{
if (strcmp(temp, p->word) == 0)
{
p->count++;
same = 1;
}
}
if (same == 0)
{
strcpy(q->word, temp);
p->next = q;
}
}
gettimeofday(&endtime, 0);
GET_TIME(starttime, endtime, durtime);
printf("wordcount: completed %ld.%ld(s)\n", durtime.tv_sec, durtime.tv_usec);
printf("wordsort: running ...\n");
gettimeofday(&starttime, 0);
/* step3: sort the results */
printf_sort(head);
gettimeofday(&endtime, 0);
GET_TIME(starttime, endtime, durtime);
printf("wordsort: completed %ld.%ld(s)\n", durtime.tv_sec, durtime.tv_usec);
/* step4: print results */
ndisp = head->count;
printf("\nwordcount: results (TOP %d from %d):\n", ndisp, len);
p = head;
if (head != NULL)
{
do
{
printf("%s - %d\n", p->word, p->count);
p = p->next;
}while (p != NULL);
}
/* step5: destroy work (e.g. free memory, close file ...) */
fclose(file);
free(head);
return 0;
}