μλ£ κ΅¬μ‘° μ€μμ λ°μ΄ν°μ λ§ν¬λ‘ ꡬμ±λ μ°κ²° 리μ€νΈ(Linked List)λΌλ κ²μ΄ μλ€. μ΄ μ°κ²°λ¦¬μ€νΈλ₯Ό μ΄λ»κ² νμ©νμ¬ λ§λλλμ λ°λΌμ μ¬λ¬ μλ£ κ΅¬μ‘°λ₯Ό λ§λ€ μ μλ€. μ΄λ²μ κ·Έ μ€μμ Stackμ λν΄μ μκΈ°νκ² λ€.
pop()
: μ€νμ κ°μ₯ μμ μλ νλͺ©μ μ κ±°νλ€.push(item)
: item νλλ₯Ό μ€νμ κ°μ₯ μ λΆλΆμ μΆκ°νλ€.peek()
: μ€νμ κ°μ₯ μμ μλ νλͺ©μ 리ν΄νλ€.is_empty()
: μ€νμ΄ λΉμ΄μμΌλ©΄ true(1)
λ₯Ό 리ν΄νλ€.typedef struct s_stack
{
int data;
struct s_stack *next;
} t_stack;
pop()
ꡬνvoid pop(t_stack *stack)
{
t_stack *node;
t_stack *prev;
if (!stack)
return ;
prev = stack;
node = stack->next;
while (node->next);
{
prev = node;
node = node->next;
}
free(node);
prev->next = NULL;
}
push(item)
ꡬνvoid push(t_stack *stack, int item)
{
t_stack *node;
t_stack *new;
node = stack;
if ((new = (t_stack *)malloc(sizeof(stack))) == 0)
return ;
new->data = item;
new->next = NULL;
while (node->next)
node = node->next;
node->next = new;
}
peek()
ꡬνint peek(t_stack *stack)
{
t_stack *node;
node = stack;
while (node->next)
node = node->next;
return (node->data);
}
is_empty()
ꡬνint is_empty(t_stack *stack)
{
if (stack == NULL)
return (1);
return (stack->next == NULL);
}
#include "stack.h"
int main(void)
{
t_stack *stack;
stack = (t_stack *)malloc(sizeof(t_stack));
for (int i = 0; i < 5; i++)
push(stack, i);
while (!is_empty(stack))
{
printf("%d ", stack.peek());
pop(stack);
}
return (0);
}
// result
// 4 3 2 1 0