본문 바로가기

IT/Algorithm

Algorithm: 큐(Queue)

동적 활당을 이용한 큐


#include <stdio.h>

#include <malloc.h>


void main(){

int n,q,qsize;

int num[100];

int *queue;

puts("How much do u want to have size of Q? ");

scanf("%d",&qsize);

queue = (int*)malloc(qsize);


for(n=0; n<100; n++){

num[n] = n;

}


for(n=0;n<100; n++){


q = n%(qsize);

queue[q] = num[n];

if(q == qsize-1){

for(q=0; q<qsize; q++){

printf("%2d ",queue[q]);

}

printf("\n");

}

}

}


링크드리스트를 이용한 큐


#include <stdio.h>

#include <malloc.h>


typedef struct _node{

int name;

struct _node *link;

}node;

node *head;



void init();

void insert(int name);

void print_node();

void del();



void main(){

int n,q,qsize;

int num[100];

init();

for(n=0; n<100; n++){

num[n] = n;

}

printf("How much do u want to have size of Q?");

scanf("%d",&qsize);


for(n=0; n<100; n++){

q = n%(qsize);

insert(num[n]);

if(q == (qsize-1)){

print_node();

del();

printf("\n");

}

}

}


void init(){

head = (node*)malloc(sizeof(node));

head->link = head;

}


void insert(int name){

node *temp;

node *h;


temp = (node*)malloc(sizeof(node));

h = head->link;

if(h->link == head){

h->link = temp;

temp->name = name;

temp->link = head;

}else if(h->link !=head){

while(h->link != head){

h = h->link;

}

h->link = temp;

temp->name = name;

temp->link = head;

}

}


void print_node(){

node *temp;

temp=head->link;

while(temp->link != head){

printf("%2d ",temp->name);

temp = temp->link;

}

printf("%2d ",temp->name);

printf("\n");

}


void del(){

node *temp;

node *del_node;

temp = head->link;

while(temp->link != head){

del_node = temp;

temp = temp->link;

free(del_node);

}

free(temp);

head->link = head;

}