linked list 설명
배열(Array) & 연결리스트(Linked List)
해당 페이지에 설명해두었음.
ft_lstnew를 구현하기 위해 libft.h파일에
typedef struct s_list { void *content; struct s_list *next; } t_list;이 구조체를 추가해야한다.
t_list *ft_lstnew(void *content)
#include "libft.h"
t_list *ft_lstnew(void *content)
{
t_list *new;
new = (t_list *)malloc(sizeof(t_list));
if (!new)
return (NULL);
new->next = NULL;
new->content = content;
return (new);
}
생성 성공시 새로 생성된 노드의 포인터를 리턴해준다.
메모리 할당 실패시 NULL을 리턴해준다.
int main(void)
{
t_list *node;
char *str = "Hello, Linked List!";
node = ft_lstnew((void *)str);
if (!node)
{
printf("Memory allocation failed.\n");
return (1);
}
printf("Node content: %s\n", (char *)(node->content)); // "Hello, Linked List!" 출력
printf("Node next: %p\n", (void *)(node->next)); // NULL
free(node);
return (0);
}