본문 바로가기

개발일기/기타

stack & queue (in c)

-stack

선입후출

top에서 삽입/삭제가 일어남

연산

push() //데이터 삽입

pop() //데이터 삭제, 반환

isempty() //스텍이 비었는지 여부 반환

//비었으면 1(true) 아니면 0(false) 반환

isfull() //스텍에 원소가 찼는지 여부 반환

//찼으면 1(true) 아니면 0(false) 반환

 

1차원 배열로 구현 -> stack.c

 

#include <stdio.h>

#define MAX_STACK_SIZE 3

#define FALSE 0
#define TRUE 1

int stack[MAX_STACK_SIZE];
int top=-1;

void push(int data);
int pop();
int isempty();
int isfull();


int main(){
    push(10);
    push(20);
    push(30);
    //push(40);

    printf("%d\n", pop());
    printf("%d\n", pop());
    printf("%d\n", pop());
    pop();
    printf("aa");

    return 0;
}

void push(int data){
    if(isfull())
        return ;
    stack[++top]=data;
}

int pop(){
    if(isempty())
        return ;
    return stack[top--];
}

int isempty(){
    if(top<0)
        return TRUE;
    else
        return FALSE;
}

int isfull(){
    if(top>MAX_STACK_SIZE)
        return TRUE;
    else
        return FALSE;
}

 

-queue

선입선출

rear에서 삽입, front에서 삭제가 일어남

 

1차원 배열로 원형큐 구현 -> queue.c

 

#include <stdio.h>
//circular queue
#define MAX_QUEUE_SIZE 10

#define FALSE 0
#define TRUE 1

int queue[MAX_QUEUE_SIZE];
int rear=-1, front=-1;

void push(int data);
int pop();
int isempty();
int isfull();


int main(){
    push(1);
    push(2);
    push(3);

    printf("%d\n", pop());
    printf("%d\n", pop());
    printf("%d\n", pop());
    

    return 0;
}

void push(int data){
    if(isfull())
        return ;
    rear=(rear+1)%MAX_QUEUE_SIZE;
    queue[rear]=data;
}

int pop(){
    if(isempty())
        return ;
    front=(front+1)%MAX_QUEUE_SIZE;
    return queue[front];
}

int isempty(){
    if(front==rear)
        return TRUE;
    else
        return FALSE;
}

int isfull(){
    if(((rear+1)%MAX_QUEUE_SIZE)==front)
        return TRUE;
    else
        return FALSE;
}

'개발일기 > 기타' 카테고리의 다른 글

software 버전 관리 - semantic versioning  (0) 2023.07.19
[vscode] 다중 주석  (0) 2023.02.16
pyplot 시도  (0) 2021.06.30
pyplot tutorial  (0) 2021.06.21
linked list stack (in c)  (0) 2021.05.18