새싹교실/2017/따라와반/과제방/자료구조/4회차 (rev. 1.3)
1. 오늘의 실습 내용 ¶
- 스택 - 배열, Linked List
- 큐 - 배열, Linked List
- 과제방에는 Linked List만 올리면 됨.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node
{
int data;
struct Node* ptr;
}Node;
Node* stack = NULL;
Node* head = NULL;
void push(int input)
{
Node* newNode;
newNode = (Node*)malloc(sizeof(Node));
newNode->data = input;
newNode->ptr = head;
head = newNode;
}
void pop()
{
Node* topNode = head;
if (head == NULL)
{
printf("-1\n");
}
else
{
int returnvalue = head->data;
head = head->ptr;
free(topNode);
printf("%d\n", returnvalue);
}
}
void print_stack()
{
Node* temp = head;
if (temp != NULL)
{
printf("Stack: ");
do
{
printf("%d ", temp->data);
temp = temp->ptr;
} while (temp != NULL);
printf("\n");
}
else
{
printf("The Stack is empty\n");
}
}
void stack_size()
{
Node* temp = head;
int cnt = 0;
while (temp != NULL)
{
cnt++;
temp = temp->ptr;
}
printf("%d\n",cnt);
}
void stack_isempty()
{
if (head == NULL)
{
printf("1\n");
}
else
{
printf("0\n");
}
}
void stack_top()
{
if (head != NULL)
{
printf("%d\n", head->data);
}
else
{
printf("-1\n");
}
}
int main()
{
int N, i, target;
char str[12];
char npush[] = "push";
char ntop[] = "top";
char nsize[] = "size";
char nempty[] = "empty";
char npop[] = "pop";
scanf(" %d", &N);
for (i = 0; i < N; i++)
{
scanf("%s", str);
if (!strcmp(str,npush))
{
scanf(" %d", &target);
push(target);
}
else if (!strcmp(str,ntop))
{
stack_top();
}
else if (!strcmp(str,nsize))
{
stack_size();
}
else if (!strcmp(str,npop))
{
pop();
}
else if (!strcmp(str,nempty))
{
stack_isempty();
}
}
return 0;
}