lstmap?

typedef struct s_list
{
	void			*content;
	struct s_list	*next;
}	t_list;
//원 함수 없음
    t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *));

구현해야할 함수 기능

: Iterates the list ’lst’ and applies the function ’f’ to the content of each element. Creates a new list resulting of the successive applications of the function ’f’. The ’del’ function is used to delete the content of an element if needed.

해석 및 부연설명

: 리스트의 모든 원소들의 content에 함수 f를 적용시키고, 그 결과로 바뀐 content들이 존재하는 새로운 리스트를 생성한다.

ex)

static void	*func(void *content)
{
	int		i;
	char	*temp;

	temp = (char *)content;
	while (temp[i])
		temp[i++] += 1;
	return (temp);
}

static void	del(void *content)
{
	free(content);
}

int	main(void)
{
	t_list	*list1;
	t_list	*list2;
	t_list	*list3;
	t_list	*newlist;

	list1 = ft_lstnew(ft_strdup("abcde"));
	list2 = ft_lstnew(ft_strdup("12345"));
	list3 = ft_lstnew(ft_strdup("!@#$"));
	list1->next = list2;
	list2->next = list3;

	newlist = ft_lstmap(list1, &func, &del);
	while (newlist)
	{
		printf("%s\n", (char *)newlist->content);
		newlist = newlist->next;
	}
}

코드 실행 결과

bcdef
12345
!@#$

리스트의 모든 원소들에 함수 func가 정상적으로 적용된 새로운 리스트가 만들어졌다.

의문점 및 생각해볼점

딱히 없다.


ft_lstmap 구현

t_list	*ft_lstmap(t_list *lst, void *(*func)(void *), void (*del)(void *))
{
	t_list	*new;
	t_list	*cur;

	new = ft_lstnew(func(lst->content));
	cur = new;
	lst = lst->next;
	while (lst)
	{
		cur->next = ft_lstnew(func(lst->content));
		cur = cur->next;
		if (cur == NULL)
		{
			ft_lstclear(&new, del);
			return (NULL);
		}
		lst = lst->next;
	}
	return (new);
}

최종적으로 새롭게 생성하여 반환할 리스트 new와 반복문을 돌리면서 사용할 리스트 cur을 따로 만들었다. 그렇게 하지 않고 new 리스트를 직접 반복문 안에서 바꾸게되면 반환값이 리스트의 끝부분이되어 원하는 결과와 달라지기 때문이다.
또한 도중에 할당에 문제가 생긴 경우 즉, cur == NULL인 경우 리스트가 정상적으로 생성되지 않은 것이므로 ft_lstclear 함수를 통해 전체 리스트를 free해준 후 NULL을 반환하도록 하였다.