Linked list
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct Node
{
int value;
struct Node *next;
};
struct Node *head;
void InitList()
{
head = (struct Node *)malloc(sizeof(struct Node));
head -> next = NULL;
}
struct Node *InsertNode(struct Node *Target, struct Node *aNode)
{
struct Node *New;
New = (struct Node *)malloc(sizeof(struct Node));
*New = *aNode;
New -> next = Target -> next;
Target -> next = New;
return New;
}
bool DeleteNode(struct Node *Target)
{
struct Node *Del;
Del = Target -> next;
if (Del == NULL)
{
return 0;
}
Target -> next = Del -> next;
free(Del);
return 1;
}
void UnInitList()
{
while (DeleteNode(head)) {;}
free(head);
head = NULL;
}
int main()
{
int i;
struct Node *Now, Temp;
InitList();
Now = head;
for (i = 1; i <= 5; i++)
{
Temp.value = i;
Now = InsertNode(Now, &Temp);
}
DeleteNode(head -> next);
for (Now = head -> next; Now; Now = Now -> next)
{
printf("%d\t", Now -> value);
}
printf("\n");
UnInitList();
}
1 3 4 5
Stack
#include <stdio.h>
#include <stdlib.h>
int *Stack;
int Size;
int Top;
void InitStack(int aSize)
{
Size = aSize;
Stack = (int *)malloc(Size * sizeof(int));
Top = -1;
}
void FreeStack()
{
free(Stack);
}
int Push(int data)
{
if (Top < Size - 1)
{
Top++;
Stack[Top] = data;
return 1;
}
else
{
return 0;
}
}
int Pop()
{
if(Top >= 0)
{
return Stack[Top--];
}
else
{
return -1;
}
}
int main()
{
InitStack(256);
Push(7);
Push(0);
Push(6);
Push(2);
Push(9);
printf("%d\n", Pop());
printf("%d\n", Pop());
printf("%d\n", Pop());
printf("%d\n", Pop());
printf("%d\n", Pop());
FreeStack();
}
9
2
6
0
7
Queue
- head : 다음 삭제될 위치. 처리할 자료를 빼낸다.
- tail : 다음 삽입될 위치. 새로 도착하는 자료가 쌓인다.
#include <stdio.h>
#include <stdlib.h>
int *Queue;
int QSize;
int head, tail;
void InitQueue(int size)
{
QSize = size;
Queue = (int *)malloc(QSize * sizeof(int));
head = tail = 0;
}
void FreeQueue()
{
free(Queue);
}
int Enqueue(int data)
{
if ((tail + 1) % QSize == head)
{
return 0;
}
Queue[tail] = data;
tail = (tail + 1) % QSize;
return 1;
}
int Dequeue()
{
int data;
if (head == tail)
{
return -1;
}
data = Queue[head];
head = (head + 1) % QSize;
return data;
}
int main()
{
int i;
InitQueue(10);
printf("빈 상태에서 삭제할 때 = %d\n", Dequeue());
for(i = 0; i < 9; i++)
{
Enqueue(i);
}
printf("가득찬 상태에서 삽입 = %s\n", Enqueue(100) ? "성공" : "실패");
for(i = 0; i < 9; i++)
{
printf("%d ", Dequeue());
}
FreeQueue();
}
빈 상태에서 삭제할 때 = -1
가득찬 상태에서 삽입 = 실패
0 1 2 3 4 5 6 7 8