10062 (Tell Me The Frequencies) - WA.. help needed..
Posted: Tue Aug 29, 2006 8:56 pm
I've searched past threads about 10062 but still couldn't figure out what's wrong with my code... I tried i/o from the problem and from some threads here, it's giving the right answer...
anyone can help? here's my code..
anyone can help? here's my code..
Code: Select all
#include <stdio.h>
#include <stdlib.h>
struct insert
{
char ascii;
int frequency;
struct insert *next;
};
typedef struct insert Insert;
typedef Insert *INSERT;
void addToList(INSERT head, INSERT newlist)
{
INSERT current, temp;
if(head->next==NULL)
{
head->next = newlist;
return;
}
else
{
if((head->next->frequency > newlist->frequency) || ((head->next->frequency == newlist->frequency) && (head->next->ascii < newlist->ascii)))
{
temp = head->next;
head->next = newlist;
newlist->next = temp;
return;
}
else
{
current = head->next;
do
{
if(current->next==NULL)
{
current->next=newlist;
return;
}
if((current->next->frequency > newlist->frequency) || ((current->next->frequency == newlist->frequency) && (current->next->ascii < newlist->ascii)))
{
temp = current->next;
current->next = newlist;
newlist->next = temp;
return;
}
else
{
current = current->next;
if(current->next == NULL)
{
current->next = newlist;
return;
}
}
}while(1);
}
}
return;
}
void printList(INSERT head)
{
INSERT current, temp; char ascii; int freq;
current = head->next;
while(current!=NULL)
{
ascii = current->ascii;
freq = current->frequency;
temp = current->next;
free(current);
current = temp;
printf("%d %d\n", ascii, freq);
}
return;
}
int main()
{
char input[129], string[1002];
int i;
INSERT head, newinsert;
head=(INSERT)malloc(sizeof(Insert));
while(gets(string)!=NULL)
{
head->next = NULL;
for(i=32;i<129;i++)
input[i]=0;
i=0;
while(string[i]!='\0')
{
input[string[i]]++;
i++;
}
for(i=32;i<129;i++)
{
if(input[i]>0)
{
newinsert = (INSERT)malloc(sizeof(Insert));
newinsert->ascii = i;
newinsert->frequency = input[i];
newinsert->next = NULL;
addToList(head,newinsert);
}
}
printList(head);
printf("\n");
}
return 0;
}