Maintaining a queue using structures in C - c

If I input 'E 5' I need to enqueue 5 onto the queue with no output. If I input 'D' I need to print the dequeued element.
Below is my code:
#include<stdio.h>
#include <stdlib.h>
typedef struct queue{
int start;//first element index
int end;//last element index
int size;//length of queue
int *ptr;//actual queue
}queue;
queue* createQueue(int x){
queue* Q=(queue*)malloc(sizeof(queue));
Q->start=0;
Q->end=0;
Q->size=1;
Q->ptr[0]=x;
return Q;
}
void enqueue(int x, queue*qptr, int i){
qptr->size++;//increase size
qptr->end++;//increase index of last element
qptr->ptr[i]=x;
return;
}
void dequeue(queue*qptr){
if(qptr->size==0){
printf("Empty\n");
return;
}
printf("%d\n",qptr->ptr[qptr->start]);
qptr->start++;
qptr->size--;
}
int main(){
char a; int i=0;int j;queue* qptr;
while(scanf("%c",&a)!=-1){
if(a=='E'){
if(i==0){
scanf("%d",&j);
qptr =createQueue(j);
i++;
}
else{
scanf("%d",&j);
enqueue(j, qptr, i);
i++;
}
}
else if(a=='D'){
if(i==0){printf("Empty\n");}
else {dequeue(qptr);i++;}
}
}
return 0;
}
I don't understand what are my errors because it seems correct to me but the code doesn't compile. Please help me.

Related

using queue and stack to reverse odd number only in a queue and other functions

#include <stdio.h>
#include <stdlib.h>
#define type int
#define qsize 40
typedef struct {
int top;
type array[qsize];
}stack;
stack *initstack (){
stack *s=malloc(sizeof(stack)); s->top =0;
return s;
}
void push(stack *s,type x){
s->array[s->top++]=x;
}
type pop(stack *s){
return s->array[--s->top];
}
type isfulls(stack *s){
return s->top>=qsize;
}
type isemptys(stack *s){
return !s->top;
}
type peek(stack *s){
return s->array[s->top-1];
}
//----------------------------------------------------
typedef struct {
type head;
type tail;
int Qnoe;
type elements[qsize];
}queue;
queue *initqueue(){
queue *s=malloc(sizeof(queue));
s->Qnoe=0; s->head=0; s->tail=-1;
return s;
}
void enqueue(queue *s,type e){
s->elements[++s->tail%qsize]=e; s->Qnoe++;
}
type dequeue(queue *s){
type temp=s->elements[s->head++%qsize];
s->Qnoe--; return temp;
}
int isempty(queue *s){
return !s->Qnoe;
}
int isfull(queue *s){
return s->Qnoe==qsize;
}
type gethead(queue *s){
return s->elements[s->head];
}
type gettail(queue *s){
return s->elements[s->tail];
}
void display(queue *s){ ///used just to display the functions
queue *temp=initqueue();
while(!isempty(s)){
type x=dequeue(s);
printf("%d ",x);
enqueue(temp,x);
}
printf("\n\n");
while(!isempty(temp)) enqueue(s,dequeue(temp));
}
int maxvalue(queue *s){
type max,head;
queue *temp=initqueue();if(!isempty(s)) {enqueue(temp,dequeue(s)); max=gethead(s);}
while (!isempty(s)){
head=gethead(s);
if(max<head) max=head;
enqueue(temp,dequeue(s));
}
while(!isempty(temp)) enqueue(s,dequeue(temp));
return max;
}
void swap(queue *s){
type head=gethead(s),tail=gettail(s);int i=0,j=1;
queue *temp=initqueue();
while(!isempty(s)) {i++; enqueue(temp,dequeue(s));}
dequeue(temp); enqueue(s,tail); ;
while(!isempty(temp)){
if(j++==i-1) {enqueue(s,head); break;}
else {enqueue(s,dequeue(temp));}
} free(temp);
}
void insert(queue *s,type e,int index){
queue *temp=initqueue(); int i=1;
while(!isempty(s)){
if(index==i++) {enqueue(temp,e); dequeue(s);}
else enqueue(temp,dequeue(s));
}
while(!isempty(temp)) enqueue(s,dequeue(temp));
}
void revercOdd(queue *s){
queue *tempq=initqueue();
stack *temps=initstack();
while(!isempty(s)){
if(gethead(s)%2){push(temps,dequeue(s)); enqueue(tempq,1);}
else enqueue(tempq,dequeue(s));
}
while(!isempty(tempq)){
if(gethead(tempq)==1){enqueue(s,pop(temps)); dequeue(tempq);}
else enqueue(s,dequeue(tempq));
}
}
int main()
{
queue *s=initqueue();
enqueue(s,5);
enqueue(s,8);
enqueue(s,3);
enqueue(s,2);
enqueue(s,1);
enqueue(s,0);
enqueue(s,112);
printf("the queue: \n");
display(s);
printf("max value in queue : %d\n\n",maxvalue(s));
swap(s);
printf("the queue after swapping the head and tail: \n");
display(s);
printf("\nthe queue: \n");
display(s);
type e,index;
printf("enter he value of the elemnt and the index: ");
scanf("%d%d",&e,&index);
insert(s,e,index);
printf("the queue after inserting %d in the index %d: \n",e,index);
display(s);
printf("\nthe queue: \n");
display(s);
revercOdd(s);
printf("the queue after reversing odd number only: \n");
display(s);
return 0;
}
I made 4 functions 1 to get the max element in the queue 1 to get swap the head and tail of the queue 1 to take an element and index and put it in that index in the queue and 1 to reverse odd numbers only in a queue using queue and stack and a function to display the element of a given queue to check results and in the main, I check the outputs of every function work on its own, but when I use them together the last display shows the garbage element in the queue:

Storing input from user into linked list using array

So I'm trying to get input from user and store it in linked list, using array (every 5 chars a new linked list is created). After getting EOF I want to print the input (actually print the arrays in each linked list)
here is my code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
typedef struct charNode {
int arr[MAX];
struct charNode *next;
} charNode;
void addNode();
void printAll();
int main(){
int c,i;
charNode *head=malloc(sizeof(charNode));
charNode *current=head;
while((c=getchar())!=EOF){
while(i<MAX){
current->arr[i++]=c;
}
i=0;
addNode(current);
}
printAll(head);
return 0;
}
void addNode(charNode *current){
struct charNode *link = (struct charNode*) malloc(sizeof(struct charNode));
current->next =link;
link->next = NULL;
current=current->next;
}
void printAll(charNode *head){
int j=0;
while(head->next!=NULL){
while(j<MAX){
printf("\n %d \t",head->arr[j++]);
}
printAll(head->next);
}
return;
}
and I'm getting "Segmentation fault (core dumped)" error..
This is Undefined behavior:
int c,i;
charNode *head=malloc(sizeof(charNode));
charNode *current=head;
while((c=getchar())!=EOF){
while(i<MAX){
current->arr[i++]=c;
}
since you are using i uninitialized to access your array, which could produce the Segmentation fault.
Change this:
printf("\n %d \t",head->arr[j++]);
to this:
printf("\n %c \t",head->arr[j++]);
so that you print characters, instead of numbers.
Simply initialize i to 0 for a start, happy debugging! =)
int main(){
char c;
charNode *head=malloc(sizeof(charNode));
charNode *current=head;
int i = 0;
while((c=getchar())!=EOF){
getchar();
while(i<MAX){
current->arr[i++]=c;
}
i=0;
addNode(&current);
}
printAll(head);
return 0;
}
void addNode(charNode **current){
struct charNode *link = malloc(sizeof(struct charNode));
link->next = NULL;
(*current)->next =link;
*current=(*current)->next;
}
void printAll(charNode *head){
int j=0;
if(head!=NULL){
while(j<MAX){
printf("%c\n",head->arr[j++]);
}
if(head->next != NULL)
printAll(head->next);
}
}
I changed your code a bit. Especially take a good look at addNode(). Now it works correctly

Malfunctioning priority queue

I've been working on some project with queue and priority queue, but I can't find a solution to a problem with priority queue. When a priority queue gets big it does not return me all the values I ask (to totalRegWait). I cut out the part where I only work with queue.
Any help regarding this question would be greatly appreciated.
Main
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "header.h"
int main()
{
ADT *attend; //Attendants
LINK *pQueue; //Priority queue
ADT *temp1; //Temporary
LINK *temp2; //Temporary
int regP; //Regular probability
int vipP; //VIP probability
int regA; //Regular attendants
int vipA; //VIP attendants
int sumA; //Combined attendants
int regT; //Regular time
int vipT; //VIP time
int bankT; //Bank working time
int i;
int attWait=0, attWait2=0; //Attendants wait time
int overtime=0, overtime2=0; //Attendants overtime
int totalRegWait=0, totalRegWait2=0; //Total regular client waiting time
int regCount=0; //Regular person count
int vipWait=0, vipWait2=0; //Maximum VIP waiting time
int vipCount=0; //Amount of VIP
getArguments(&regP, &vipP, &regA, &vipA, &regT, &vipT, &bankT);
sumA=regA+vipA;
create(&attend);
for(i=0;i<sumA;i++){
enq(&attend, 0);
}
createEmpty(&pQueue);
srand(time(NULL));
for(i=0;i<bankT;i++){
if(rand()%100<regP){
regCount++;
add(&pQueue, 0, 0);
}
if(rand()%100<vipP){
vipCount++;
add(&pQueue, 1, 0);
}
//1st method
first(&attend, &pQueue, vipT, regT, &vipWait, &totalRegWait, &attWait);
}
printf("%d %d\n", regCount, vipCount);
printf("%d %d\n", totalRegWait, totalRegWait2);
//Printing results
printf("First method:\n");
printResults(attWait, overtime, totalRegWait, regCount, vipWait, vipCount);
return 0;
}
Functions
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
void createEmpty(LINK **head) {
(*head)=NULL;
}
void add(LINK **head, int p, DATA v){
LINK *curr=(*head);
LINK *beforeCurr=(*head);
LINK *newElement;
newElement=(LINK*)malloc(sizeof(LINK));
if(newElement==NULL){
printf("Error. Not enough memory to allocate.\n");
}
newElement->priority=p;
newElement->value=v;
newElement->next=NULL;
if((*head)==NULL){
(*head)=newElement;
}
else if(p<(*head)->priority){
newElement->next=curr;
(*head)=newElement;
}
else{
while(p>(curr->priority) && curr->next!=NULL){
beforeCurr=curr;
curr=curr->next;
}
if(curr->next==NULL && p>(curr->priority))
(curr->next)=newElement;
else if(curr==(*head)){
newElement->next=curr;
(*head)=newElement;
}
else{
beforeCurr->next=newElement;
newElement->next=curr;
}
}
}
void pop(LINK **head, int *p, DATA *v, int *error){
LINK *curr=(*head);
LINK *currB=(*head);
if(*head==NULL){
(*error)=1;
}
else if(curr->next==NULL){
(*p)=curr->priority;
(*v)=curr->value;
free(curr);
(*head)=NULL;
}
else{
while(curr->next!=NULL) {
currB=curr;
curr=curr->next;
}
(*p)=curr->priority;
(*v)=curr->value;
free(curr);
currB->next=NULL;
}
}
int checkIfEmpty(LINK *head){ //Working
if(head==NULL)
return 1;
else
return 0;
}
//-------------------------------
void create(ADT **front){ //Working
*front = NULL;
}
void enq(ADT **front, QDATA variable){ //Should be good
ADT *temp;
ADT *rear = (ADT *)malloc(sizeof(ADT));
if(rear==NULL){
printf("Error. Not enough memory to allocate.\n");
}
if(*front == NULL)
{
*front = (ADT *)malloc(sizeof(ADT));
if(*front==NULL){
printf("Error. Not enough memory to allocate.\n");
}
(*front)->var = variable;
(*front)->next = NULL;
}
else
{
temp = *front;
while(temp->next != NULL){
temp = temp->next;
}
rear->var = variable;
rear->next = NULL;
temp->next = rear;
}
}
//--------------------------------
void first(ADT **attend, LINK **pQueue, int vipT, int regT, int *vipWait, int *totalRegWait, int *attWait){
ADT *temp1;
LINK *temp2;
int priority;
DATA value;
int error=0;
if(checkIfEmpty(*pQueue)==1){ //If client's queue is empty, time is changed to attenders and increased att. waiting time
temp1=(*attend);
while(temp1 != NULL){
if((temp1->var)>0){
(temp1->var)--;
}
else{
(*attWait)++;
}
temp1 = temp1->next;
}
}
else{ //If there are clients, look for not occupied attenders
temp1=(*attend);
temp2=(*pQueue);
while(temp1 != NULL){ //While loop which goes through all the attenders
if((temp1->var)>0){ //If attender is busy
(temp1->var)--; //Yes, then it's value is decreased by 1
}
else{ //If attender value is not busy
if(checkIfEmpty(*pQueue)==1){ //Check if priority line is empty
(*attWait)++; //If yes, waiting time for attenders is added
}
else{ //If priority line is not empty
pop(&(*pQueue), &priority, &value, &error); //Client is removed from queue
printf("%d %d\n", priority, value);
if(error==1){ //If pop fails it shows an error and quit
printf("Error\n");
return 0;
}
else{ //If pop does not fail
if(priority==1){ //Check if client is VIP
temp1->var=vipT; //If yes, then attender is given VIP time to his value
if((*vipWait)<value){ //If VIP client's waiting time is higher than earlier value
(*vipWait)=value; //Earlier VIP waiting time is changed
}
}
if(priority==0){ //If client is regular
temp1->var=regT;
(*totalRegWait)=(*totalRegWait)+value; //Removed client's waiting value is added to a total value
(temp1->var)--;
}
(temp1->var)--; //Attender time is lowered by 1 (end of minute)
}
}
}
temp1 = temp1->next; //Going for another attender
}
if(checkIfEmpty(*pQueue)==0){ //Check if priority queue is empty
while(temp2!=NULL) {
(temp2->value)++; //Waiting time to a client is added
temp2 = temp2->next; //Next client
}
}
}
}
Header
#ifndef HEADER_H_
#define HEADER_H_
typedef int DATA;
typedef int QDATA;
typedef struct priorityQueue{
int priority;
DATA value;
struct priorityQueue *next;
}LINK;
typedef struct list
{
QDATA var;
struct list *next;
}ADT;
void enq(ADT **front, QDATA variable);
void create(ADT **front);
//PRIORITY QUEUE FUNCTIONS
void createEmpty(LINK **head);
void add(LINK **head, int p, DATA v);
void pop(LINK **head, int *p, DATA *v, int *error);
int checkIfEmpty(LINK *head);
//END OF PRIOR. QUEUE FUNCTIONS
void first(ADT **attend, LINK **pQueue, int vipT, int regT, int *vipWait, int *totalRegWait, int *attWait);
#endif

Queue Implementation Trouble C

I'm having issues implementing a FIFO queue in C that acts as a circular buffer.. I have only managed to write an enqueue method so far and I'm having problems with the output. It doesn't display what it should and I'm not sure where the problem lies.
The code is as follows:
struct queue
{
int array[30];
int *front; //pointer to front of queue
int *rear; //pointer to rear of queue
int count; //counts number of elements in queue
};
//initialising a queue
struct queue *init_Queue(){
struct queue * q = malloc(sizeof (q));
q->count=0;
q->front=q->array;
q->rear=q->array;
return q;
}
int isFull(struct queue *q){
if(q->count==30){
printf("\n Buffer is full!");
return 1;
}
return 0;
}
int isEmpty(struct queue *q){
if(q->count==0){
printf("\n Buffer is empty!");
return 1;
}
return 0;
}
int enqueue(struct queue * q,int i){
if(isFull(q)){
return 0;
}
if(isEmpty(q)){
q->front+1;
}
int k=*(q->rear)+1;
printf("\n %d",k);
q->array[k]=i;
q->rear+1;
printf("\n Enqueue success!");
q->count++;
return 1;
}
int main(int argc, char**argv)
{
int i=10;
int k=12;
struct queue *q=init_Queue();
enqueue(q,i);
int j= q->count;
printf("\n %d",j);
printf("\n %d",q->array[0]);
printf("\n %d",q->rear);
enqueue(q,k);
int z= q->count;
printf("\n %d", z);
printf("\n %d", q->array[1]);
printf("\n %d",q->rear);
free(q);
}
The output is as follows:
Buffer is empty!
1
Enqueue success!
1 <<**value of count**
0 << **value stored in array[0]...it should say 10**
1070400 << **q->rear...should be pointing to 10?**
1
Enqueue success!
2 **<<value of count**
12 **<<value stored in array[1]**
1070400 **<< q-rear...should be incremented and pointing to 12?**
Program ended with exit code: 0
q->rear+1;
This do nothing
if(isEmpty(q)){
q->front+1;
}
Why ?
My proposition:
int enqueue(struct queue * q,int i){
if(isFull(q)){
return 0;
}
if(!isEmpty(q)){
q->rear++;
}
*(q->rear) = i;
printf("\n Enqueue success!");
q->count++;
return 1;
}
remark prefer return 0 on success and another on error like -1

Lattices of Partial Order Set Segmentation Fault(core dumped)

Given a Set S = {x1,x2,x3,x4,x5,….} whose size is n (< 20), I need to list all the lattices (subsets of S) on S with size k(should be taken as input, but in my question I fixed it for debugging purposes). The relation over which the partial order is defined is divisibility.
#include <stdio.h>
#include <stdbool.h>
typedef struct{
int data;
struct node* next;
}node;
void addEdge(node* graph[],int a,int b){
node *ptr=(node *)malloc(sizeof(node));
ptr->next=graph[a];
ptr->data=b;
graph[a]=ptr;
}
void buildGraph(node* graph[],int n){
int i,j;
for(i=2;i<=n;i++){
for(j=1;j<=i/2;j++){
if(i%j==0){
if(j!=1) addEdge(graph,i/j,i);
else addEdge(graph,j,i);
}
}
}
}
void printGraph(node* graph[],int n){
int i=0;
node *ptr;
for(i=0;i<=n;i++){
ptr=graph[i];
printf("Row-%d ",i);
while(ptr!=NULL){
printf("%d ",ptr->data);
ptr=ptr->next;
}
printf("\n");
}
}
void print(int array[],int n){
int i;
for(i=0;i<n;i++) printf("%d ",array[i]);
printf("\n");
}
bool checkDuplicate(int array[],int n,int a){
int i;
for(i=0;i<n;i++) if(array[i]==a) return false;
return true;
}
void formLattice(node* graph[],int lattice[],int k,int vertex,int level){
//printf("Level-%d \n",level);
if(level>k) return;
if(level==k) {
lattice[level-1]=vertex;
print(lattice,k);
return;
}
lattice[level-1]=vertex;
node* ptr=graph[vertex];
while(ptr!=NULL){
// if(checkDuplicate(lattice,level,ptr->data))
formLattice(graph,lattice,k,ptr->data,level+1);
ptr=ptr->next;
}
}
void printLattice(node* graph[],int n,int k){
int lattice[k],i;
node* ptr;
for(i=1;i<=n;i++){
ptr=graph[i];
while(ptr!=NULL){
lattice[0]=i;
formLattice(graph,lattice,k,ptr->data,2);
ptr=ptr->next;
}
}
}
int main(void) {
int n=10,k=4;
node* graph[n+1];
int i;
for(i=0;i<=n;i++) graph[i]=NULL;
buildGraph(graph,n);
// printGraph(graph,n); // Comment to print out the Hasse Diagram
printLattice(graph,n,k);
return 0;
}
Showing Segementation Fault(core dumped)
Any idea why is this happening so?
Thanks in Advance
The code of formLattice() has evidences that only those vertexes are probed for lattice[level] that are connected to lattice[level-1]. Not every lattice, of course, has a total order on it (namely {1,2,3,6} doesnt). How can the present program choose the vertex 3 for lattice[2] while the vertex 2 is stored into lattice[1]?
In other words, there must be another loop, going for all already chosen vertexes in lattice from 0 to level-1, around the present loop for ptr.

Resources