728x90
반응형
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char element;
typedef struct stacknode {
element data;
struct stacknode* link;
} stacknode;
stacknode* top;
void push(element item) {
stacknode* temp = (stacknode*)malloc(sizeof(stacknode));
temp->data = item;
temp->link = top;
top = temp;
}
element pop() {
element item;
stacknode* temp = top;
if (top == NULL) {
printf("\n Stack is empty !\n");
return 0;
}
else {
item = temp->data;
top = temp->link;
free(temp);
return item;
}
}
element peek() {
element item;
if (top == NULL) {
printf("\n Stack is empty !\n");
return 0;
}
else {
item = top->data;
return item;
}
}
void del() {
stacknode* temp;
if (top == NULL)
printf("\n Stack is empty !\n");
else {
temp = top;
top = top->link;
free(temp);
}
}
void printstack() {
stacknode* p = top;
printf("\n STACK [ ");
while (p) {
printf("%c ", p->data);
p = p->link;
}
printf("] ");
}
void main(void) {
element item;
top = NULL; printstack();
push('A'); printstack();
push('B'); printstack();
push('C'); printstack();
item = peek();
printstack();
printf("peek top => %c\n", item);
del();
printstack();
item = pop();
printstack();
printf("\t pop top => %c\n", item);
item = pop();
printstack();
printf("\t pop top => %c\n", item);
pop();
}
이 코드는 스택 자료구조를 구현한 코드입니다. 스택은 데이터를 쌓아 올리는 자료구조로, 가장 마지막에 쌓은 데이터를 가장 먼저 꺼내는 Last In First Out(LIFO) 방식으로 동작합니다.
먼저 코드의 구조를 살펴보면, 스택 노드를 구조체로 정의하고 있습니다. 스택 노드는 데이터와 다음 노드를 가리키는 포인터로 구성되어 있습니다. 이후에는 스택 자료구조의 기본 연산인 push, pop, peek, del, printstack을 구현하고 있습니다.
push 연산은 새로운 데이터를 스택의 맨 위에 추가하는 연산입니다. 이때, 동적 메모리 할당을 이용하여 새로운 노드를 생성하고, 이전 노드를 가리키도록 합니다.
pop 연산은 스택의 맨 위에 있는 데이터를 제거하고 반환하는 연산입니다. 이때, 마찬가지로 동적 메모리 할당을 이용하여 제거된 노드를 메모리에서 해제합니다.
peek 연산은 스택의 맨 위에 있는 데이터를 반환하는 연산입니다. 이때, 스택이 비어있는 경우 예외 처리를 해줍니다.
del 연산은 스택의 맨 위에 있는 데이터를 제거하는 연산입니다. 이때, pop 연산과는 달리 반환하는 데이터가 없습니다.
printstack 연산은 현재 스택에 있는 데이터를 출력하는 연산입니다.
마지막으로, main 함수에서는 위에서 구현한 연산들을 이용하여 스택을 구현하고, 각 연산의 결과를 출력합니다.
728x90
반응형
'CS > 자료구조' 카테고리의 다른 글
자료구조 C언어 스택(Stack) 예제 (0) | 2023.05.04 |
---|---|
자료구조 C언어 데크(Deque, Double-ended Queue) 예제 (0) | 2023.05.04 |
자료구조 C언어 큐(Queue) 예제 (0) | 2023.05.04 |
C언어 자료구조 배열로 구현된 스택의 삽입/삭제 (0) | 2023.05.03 |