typedef struct s_node
{
int data;
struct s_node *next;
struct s_node *prev;
} t_node;
typedef struct s_ps
{
int count;
t_node *head;
} t_ps;
같은 구조체를 사용해 연결 리스트를 구현했었으나, 마지막 연결 리스트에 대한 처리가 미흡해서 leak 처리가 어려워서 deck 구조를 사용하기로 했습니다.
덱 자료구조를 사용하며 필요한 기본 함수를 미리 설정해 뒀습니다.
양방향으로 입력과 출력이 가능하여 create, left_push, left_pop, right_push, right_pop 5가지를 기본으로 설정해뒀습니다.
t_ps *ps_create(void)
{
t_ps *ps;
ps = (t_ps *)ft_calloc(1, sizeof(t_ps));
if (!ps)
ps_error(2);
return (ps);
}
int ps_left_add(t_ps *ps, int data)
{
t_node *buf;
t_node *new;
new = (t_node *)ft_calloc(1, sizeof(t_node));
if (!new)
return (FALSE);
new->data = data;
if (ps->count == 0)
ps->head = new;
else
{
buf = ps->head;
buf->prev = new;
new->next = buf;
ps->head = new;
}
ps->count += 1;
return (TRUE);
}
int ps_right_add(t_ps *ps, int data)
{
t_node *buf;
t_node *new;
new = (t_node *)ft_calloc(1, sizeof(t_node));
if (!new)
return (FALSE);
new->data = data;
if (ps->count == 0)
ps->head = new;
else
{
buf = ps_get_node(ps, ps->count - 1);
buf->next = new;
new->prev = buf;
}
ps->count += 1;
return (TRUE);
}
t_node *ps_left_pop(t_ps *ps)
{
t_node *buf;
if (!ps->count)
return (NULL);
buf = ps->head;
ps->head = buf->next;
if (ps->count != 1)
ps->head->prev = NULL;
buf->prev = NULL;
buf->next = NULL;
ps->count -= 1;
return (buf);
}
t_node *ps_right_pop(t_ps *ps)
{
t_node *buf;
if (ps->count == 0)
return (NULL);
buf = ps_get_node(ps, ps->count - 1);
if (ps->count == 1)
ps->head = NULL;
else
buf->prev->next = NULL;
buf->prev = NULL;
buf->next = NULL;
ps->count -= 1;
return (buf);
}
t_node *ps_get_node(t_ps *ps, int position)
{
t_node *buf;
if (ps->count == 0)
return (NULL);
buf = ps->head;
while (position--)
buf = buf->next;
return (buf);
}