ft_lstlast

Subject

Nome da função: ft_lstlast

Protótipo: t_list *ft_lstlast(t_list *lst);

Parâmetros:

  • #1. O começo da lista.

Valor de retorno: O último elemento da lista.

Funções externas: Nenhuma.

Descrição: Retorna o último elemento da lista.

Rascunho

A função pede para acharmos o último elemento da lista. Dessa forma, devemos ir avançando até encontrar o último. Se fizéssemos um main assim:

int main() {
  
  t_list    *l;
  t_list *final;
    
  l = ft_lstnew(strdup("1"));
  l->next = ft_lstnew(strdup("2"));
  l->next->next = ft_lstnew(strdup("3"));

  final = ft_lstlast(l);

  return 0;
}

O resultado seria:

Criando uma lista ‘l’ com três elementos
‘aux’ vai avançando até chegar no último elemento que é 51.

Código

t_list	*ft_lstlast(t_list *lst)
{
	t_list	*aux; //criando uma lista auxiliar

	aux = lst; //fazendo ter o mesmo endereço
	if (lst) //se o endereço não for nulo
		while (aux->next) //enquanto tiver como avançar
			aux = aux->next; //avanço
	return (aux); //retorna o último elemento
}

Deixe um comentário