ft_lstlast

jaehlee·2025년 4월 27일

Libft

목록 보기
20/26

linked list 설명

배열(Array) & 연결리스트(Linked List)
해당 페이지에 설명해두었음.

ft_lstlast를 구현하기 위해 libft.h파일에

typedef struct s_list
{
	void			*content;
	struct s_list	*next;
}					t_list;

이 구조체를 추가해야한다.

1. ft_lstlast란?


ft_lstlast는 연결 리스트에서 마지막 노드를 찾아 리턴하는 함수이다.

2. 함수 프로토타입

t_list	*ft_lstlast(t_list *lst);

3. 함수구현

#include "libft.h"

t_list	*ft_lstlast(t_list *lst)
{
	if (!lst)
		return (NULL);
	while (lst->next != NULL)
		lst = lst->next;
	return (lst);
}

사용예시

int main(void)
{
	t_list *list = NULL;
	t_list *node1;
	t_list *node2;
	t_list *node3;
	t_list *last;

	node1 = ft_lstnew("first");
	node2 = ft_lstnew("second");
	node3 = ft_lstnew("third");

	ft_lstadd_front(&list, node2); // 리스트: second
	ft_lstadd_front(&list, node1); // 리스트: first -> second
	ft_lstadd_front(&list, node3); // 리스트: third -> first -> second

	last = ft_lstlast(list);

	if (last)
		printf("Last node content: %s\n", (char *)last->content); // "second" 출력
	else
		printf("List is empty.\n");

	free(node1);
	free(node2);
	free(node3);
	return (0);
}
profile
공부하는 개발자

0개의 댓글