Hej, muszę napisać listę jednokierunkową z napisami i ilością ich wystąpień. Dodawanie elementów ma być połączone z sortowaniem ich. Rozwiązałem prawie całą część problemu, niestety jeżeli chcę dodać jakiś wyraz leksykograficznie wyższy niż te, które są na liście, to program się wysypuje. Siedziałem trochę nad tym i trudno mi wymyśleć rozwiązanie, tym bardziej że sprawa komplikuje się przez nulla, który jest końcem tej listy...
Czy ktoś mógłby mi rzucić pomysł, byłbym wdzięczny za jakiś pseudokod czy cokolwiek.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
struct element
{
char *word;
unsigned int arity;
struct element *next;
};
struct element *head;
void dopisz();
void usun();
void wyswietl();
int main()
{
head = (struct element*)malloc(sizeof(struct element));
head = NULL;
int isEnd = FALSE, answer;
while(!isEnd)
{
printf("\n\t\tMENU\n");
printf("[0] - zakonczenie programu\n");
printf("[1] - dopisanie wyrazu\n");
printf("[2] - usuniecie wyrazu\n");
printf("[3] - wyswietlenie zawartosci listy\n");
scanf("%d", &answer); getchar();
switch(answer)
{
case 0:
printf("Zakonczenie!\n");
isEnd=TRUE;
break;
case 1:
dopisz();
break;
case 2:
usun();
break;
case 3:
wyswietl();
break;
default:
printf("Bledny wybor...\n");
}
}
return 0;
}
void dopisz()
{
char bufor[31];
struct element *new;
new = (struct element*)malloc(sizeof(struct element));
if(new == NULL)
{
printf("Brak pamieci\n");
}
printf("Wyraz: ");
scanf("%s", bufor); getchar();
new->word = (char*)malloc(sizeof(char)*strlen(bufor));
strcpy(new->word, bufor);
new->arity=1;
struct element *temp;
for(temp=head; temp!=NULL; temp=temp->next)
{
if(strcmp(new->word, temp->word)==0)
{
temp->arity++;
free(new);
return;
}
else if( (head==NULL) )
// lub else if( (head==NULL) || (strcmp(new->word, head->word)<0) )
{
new->next=head;
head = new;
return;
}
else if((strcmp(new->word, temp->word)>0) && (strcmp(new->word, temp->next->word)<0))
{
struct element *pom;
pom = temp->next;
temp->next = new;
new->next = pom;
return;
}
// else if(temp->next==NULL)
// {
// head->next = new;
// new->next = NULL;
// head=new;
// return;
// }
}
// new->next=head;
// head = new;
}
void usun()
{
char bufor[31];
printf("\nJaki wyraz usunac?\t");
scanf("%s", bufor); getchar();
struct element *temp;
for(temp=head; temp!=NULL; temp=temp->next)
{
if(strcmp(temp->word, bufor)==0)
{
if(temp->arity>1)
{
temp->arity--;
printf("Zmniejszono ilosc wystapien wyrazu o 1.\n");
return;
}
else
{
struct element *pom;
pom = head;
head = pom->next;
free(pom);
printf("Usunieto wyraz.\n");
return;
}
}
}
printf("Nie ma takiego wyrazu!\n");
}
void wyswietl()
{
struct element *temp;
printf("\n");
if(head==NULL)
printf("Lista pusta\n");
for (temp=head; temp!=NULL; temp=temp->next)
{
printf("%s\t%d\t adres: %p\t \n", temp->word, temp->arity, temp);
}
}
Pozdrawiam.