-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2729.c
More file actions
99 lines (72 loc) · 1.92 KB
/
2729.c
File metadata and controls
99 lines (72 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct lista{
char item[21];
struct lista* prox;
}Lista_de_compras;
Lista_de_compras* add_item(Lista_de_compras* lista, char item[21]){
Lista_de_compras* atual = lista;
Lista_de_compras* ant = NULL;
int k;
while(atual != NULL){
k = strcmp(item, atual->item);
if(k == 0){
return lista; //Item igual, nao adicona na lista
}
else if(k < 0){
break; //O novo item deve vir antes do item atual
}
else{
//Item deve ficar depois do item atual
ant = atual;
atual = atual->prox;
}
}
Lista_de_compras* novo_item = (Lista_de_compras*)malloc(sizeof(Lista_de_compras));
strcpy(novo_item->item, item);
novo_item->prox = atual;
if(ant == NULL){ //Se ant = NULL, o novo item deve ficar no inicio da lista
return novo_item;
}
else{ //Se nao o ant deve apontar pro novo item e retornar o inicio normal da lista
ant->prox = novo_item;
return lista;
}
}
void print_lista(Lista_de_compras* lista){
while(lista != NULL){
if(lista->prox == NULL) printf("%s", lista->item);
else printf("%s ", lista->item);
lista = lista->prox;
}
printf("\n");
}
void free_lista(Lista_de_compras* lista){
Lista_de_compras* ant;
while(lista != NULL){
ant = lista->prox;
free(lista);
lista = ant;
}
}
int main(){
Lista_de_compras* lista = NULL;
char string[21];
char x = ' ';
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
lista = NULL;
while(x != '\n'){
scanf("%s", string);
x = getchar(); //captura o \n do buffer
lista = add_item(lista, string);
}
print_lista(lista);
x = ' ';
free_lista(lista);
}
return 0;
}