How to remove the smallest element in a dynamic/chained C list (TAD)

Asked

Viewed 367 times

1

"Create an unordered list TAD by implementing the minor function (removes the smallest element from a list) dynamic/chained".

int menor_elem(Lista *lst){
Lista aux = *lst;
if (lista_vazia(*lst) == 1) 
    return 0;

I don’t know how I do the repetition to find and save the previous pointer from the smallest element!! PFF explain the code because I’m not finding a solution!

EDITED: I already did . H with typedef and user. c does not matter for exercise! i tried to do the men_elem but do not know how it continues (I just need to do the function that removes the smallest element from the list ).

I have already created the list, I have checked if it is empty, I have done the function that removes and adds an element and I have already made a function that shows the size of the list, only the function that removes the smallest element is missing.

#include <stdio.h>
#include <stdlib.h>
#include "lista.h"

struct no {
int info;
struct no *prox;
};

Lista cria_lista(){
return NULL;
}

int lista_vazia(Lista lst){
if (lst == NULL)
    return 1;
else
    return 0;
}

int insere_elem(Lista *lst, int elem){
Lista N = (Lista) malloc(sizeof(struct no));
if (N == NULL)
    return 0;
N->info = elem;
N->prox = *lst;
*lst = N;
return 1;
}

int remove_elem (Lista *lst, int elem) {
if (lista_vazia(*lst) == 1) {return 0;}
Lista aux = *lst;
if (elem == (*lst)->info) {
    *lst = aux->prox;
    free(aux);
    return 1;
}
while (aux->prox != NULL && aux->prox->info != elem)
    aux = aux->prox;
if (aux->prox == NULL)
    return 0;
Lista aux2 = aux->prox;
aux->prox = aux2->prox;
free(aux2);
return 1;
}

int imprime_lista(Lista lst){
Lista aux = lst;
if (lista_vazia(lst) == 1){
    printf(" -[ ]-\n");
    return 0;
}
printf(" -[");
while (aux!= NULL){
    printf(" %d",aux->info);
    aux = aux->prox;
    }
    printf(" ]- \n");
}

int tamanho_lista(Lista lst){
Lista aux = lst;
if (lista_vazia(lst)==1){
    printf("A lista tem 0 elementos\n");
    return 0;
    }
int x=0;
while(aux!= NULL){
    x++;
    aux = aux->prox;
}
printf("A lista tem %d elementos\n",x);
 }
  • Are you required to use this piece of the function? Have you written anything from TAD? if yes would like to know in which way you are using List.

  • The beginning of the function I tried to do, but I don’t need to use it. !

1 answer

1

I got !!

int menor_elem(Lista *lst){
if (lista_vazia(*lst) == 1)
    return 0;
Lista aux = *lst;
int x;
x = aux->info;
while (aux->prox != NULL){
    if (aux->info < x)
        x = aux->info;
    aux = aux->prox;
}
remove_elem(lst, x);
return 1;

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.