Lab_Capture-4 :: Queue

November 26, 2012 6:39 pm C, Homework, Private

Host by img.kusumoto.co

#include <stdio.h>
typedef struct head {
	struct node *front;
	int count;
	struct node *rear;
}HEAD;
 
typedef struct node {
	int data;
	struct node *next;
}NODE;
//start PrintQueue
void PrintQueue(HEAD *headNode) {
	NODE *printNode=headNode->front;
	int numberOfQueue = headNode->count;
	int tempData[numberOfQueue];
 
	printf("\n----------Print Queue-----------\n");
	while(printNode!=NULL) {
		//get data into array for display
		tempData[numberOfQueue-1] = printNode->data;
		printNode = printNode->next;
		numberOfQueue--;
	}
	int i;
	for(i=0;i<headNode->count;i++) {
		printf(" | %d | \n",tempData[i]);
	      }
	   printf("-----------------------------\n");
	}
 
//end PrintQueue
//start Enqueue
void Enqueue(HEAD *headNode,int data) {
	//create new node
	NODE *newNode;
	newNode = (NODE*)malloc(sizeof(NODE));
	//set data
	newNode->data = data;
	//set link new node to NULL
	newNode->next = NULL;
	//link rear node ,to new node
	if(headNode->rear==NULL) {
		//in case first node
		headNode->front = newNode;
		headNode->rear = newNode;
	}else{
			headNode->rear->next = newNode;
	}
	//set new node is rear
	headNode->rear = newNode;
	//increase count
	headNode->count++;
	//print rear node
	printf("\n Enqueue node | %d | ln \n",newNode->data);
	PrintQueue(headNode);
	}
	//end Enqueue
	//start Dequeue
	void Dequeue(HEAD *headNode) {
		//get front node
		NODE *frontNode = headNode->front;
		//set front node to next node
		headNode->front = frontNode->next;
		//decrease count
		headNode->count--;
		//check is last node
		if(headNode->count==0)
			headNode->rear = NULL;
		//print front node
		printf("\n Dequeue node | %d | out \n",frontNode->data);
		PrintQueue(headNode);
	}
//end Dequeue
 
main() {
	HEAD *headNode;
	headNode = (HEAD*)malloc(sizeof(HEAD));
	headNode->count=0;
	headNode->front=NULL;
	headNode->rear=NULL;
	Enqueue(headNode,2);
	Enqueue(headNode,4);
	Enqueue(headNode,6);
	Enqueue(headNode,8);
	Enqueue(headNode,10);
	Enqueue(headNode,12);
 
	Dequeue(headNode);
	Dequeue(headNode);
 
 
}