init
push
pop
empty
top
peek
를 이용해서 만들었다.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef int element;
typedef struct Node
{
struct Node *link;
element item;
} Node;
typedef struct
{
Node *top;
} Stack;
void init(Stack *s) ////////////왜 초기화 안 해도 되는 거지?
{
s->top = NULL;
}
int is_empty(Stack *s)
{
return (s->top == NULL);
}
void push(Stack *s, element item)
{
Node *temp = (Node *)malloc(sizeof(Node));
if (temp == NULL)
{
fprintf(stderr, "메모리할당에러\n");
return;
}
else
{
temp->item = item;
temp->link = s->top;
s->top = temp;
}
}
element pop(Stack *s)
{
if (is_empty(s))
{
return -1;
}
else
{
Node *temp = s->top;
element item = temp->item;
s->top = s->top->link;
free(temp); // 이렇게 해도 되는 구나..
return item;
}
}
int size(Stack *s)
{
int size = 0;
for (Node *p = s->top; p != NULL; p = p->link) // 여기서 p->link랑 p != NULL
{
size++;
}
return size;
}
int main()
{
int N, num;
scanf("%d", &N);
Stack *s = (Stack *)malloc(sizeof(Stack));
char *cmd = (char *)malloc(sizeof(char) * N);
for (int i = 0; i < N; i++)
{
scanf("%s", cmd + i);
if (strcmp(cmd + i, "push") == 0)
{
scanf("%d", &num);
push(s, num);
}
else if (strcmp(cmd + i, "top") == 0)
{
if (is_empty(s))
printf("-1\n");
else
printf("%d\n", s->top->item);
}
else if (strcmp(cmd + i, "size") == 0)
{
printf("%d\n", size(s));
}
else if (strcmp(cmd + i, "empty") == 0)
{
if (is_empty(s))
printf("1\n");
else
printf("0\n");
}
else if (strcmp(cmd + i, "pop") == 0)
{
printf("%d\n", pop(s));
}
}
free(s);
return 0;
}
출력을 할 때 위와 같이 출력해야 하는 줄 알고 아래와 같이 만들었다..
char *result = (char *)malloc(sizeof(char) * N);
for (int i = 0; i < N; i++)
{
scanf("%s", cmd + i);
if (strcmp(cmd + i, "push") == 0)
{
scanf("%d", &num);
push(s, num);
i--; ///////////////여기서 i와 N을 빼니까 result에 원하는 값만 담을 수 있으므로 진짜 잘 했다고 생각했지만,,
N--;
}
else if (strcmp(cmd + i, "top") == 0)
{
if (is_empty(s))
*(result+i) =-1;
else
*(result+i) =s->top->item;
}
}
C는 스택을 하나하나 만들어야 해서 불편한가?
다음에는 1. 연결리스트 스택(top pointer 있는)
2. 연결리스트 스택(top pointer 없는)
3. 배열 스택
의 속도 차이를 비교해보고 싶다.
아직 init(s)
을 왜 안 해도 되는지 모르겠다..
틀린 부분은 지적해주세요