Aline na verdade você tem que ter o ponteiro que aponta para o seu elemento e vc consegue através do ponteiro “próximo” saber qual é o elemento seguinte, certo? A partir daí vc pode trocar os conteúdos através de trocas simples mesmo, tipo:
String tmp = atual.getElemento();
atual.setElemento(proximo.getElemento());
proximo.setelemento(tmp);
3 Comments
Boa noite. Como usar o bublle sort em lista encadeada de string?
Aline na verdade você tem que ter o ponteiro que aponta para o seu elemento e vc consegue através do ponteiro “próximo” saber qual é o elemento seguinte, certo? A partir daí vc pode trocar os conteúdos através de trocas simples mesmo, tipo:
String tmp = atual.getElemento();
atual.setElemento(proximo.getElemento());
proximo.setelemento(tmp);
ajudei?
Aline, se for em C, fica assim:
main.c
#include <stdio.h>
#include <string.h>
#include “list.h”
LIST list;
int main(void) {
init(&list);
insert(&list, “Practice”);
insert(&list, “Coding”);
insert(&list, “Quiz”);
insert(&list, “Debugging”);
insert(&list, “C++”);
insert(&list, “C”);
sort(&list);
print_list(&list);
return 0;
}
list.h
struct node{
struct node *next;
char *value;
};
struct list{
struct node *start;
};
typedef struct node NODE;
typedef struct list LIST;
void init(LIST *list);
void insert(LIST *list, char *string);
int length(LIST *list);
void sort(LIST *list);
void print_list(LIST *list);
list.c
#include <stdlib.h>
#include <string.h>
#include “list.h”
void init(LIST *list){
list->start = NULL;
}
void insert(LIST *list, char *string){
NODE *new_node = (NODE *)calloc(1,sizeof(NODE));
new_node->value = (char *)calloc(strlen(string),sizeof(char));
strcpy(new_node->value,string);
new_node->next = NULL;
if(list->start == NULL){
list->start = new_node;
}else{
NODE *aux = list->start;
while(aux->next != NULL){
aux = aux->next;
}
aux->next = new_node;
}
}
int length(LIST *list){
NODE *aux = list->start;
int count = 0;
while(aux != NULL){
count += 1;
aux = aux->next;
}
return count;
}
void sort(LIST *list){
int count = length(list);
for(int iterations = 0; iterations start;
for(int i = 0; i value,aux->next->value) > 0){
char *temp = (char *)calloc(strlen(aux->value),sizeof(char));
strcpy(temp,aux->value);
strcpy(aux->value,aux->next->value);
strcpy(aux->next->value,temp);
}
}
}
}
void print_list(LIST *list){
NODE *aux = list->start;
while(aux != NULL){
printf(“%s\n”,aux->value);
aux = aux->next;
}
}