can any body help in implementing linked queues and also iterating it from the external main program????:?:

Dani AI

Generated

Responding to : a linked queue is just a singly linked list with both front and rear pointers. Two common external-iteration patterns are (a) expose the node pointer so main can walk front->next... (simple but breaks encapsulation) or (b) keep the structure opaque and provide a safe iterator or a foreach callback. 's terse "no" is not useful; was right to ask for willingness to learn — below is a compact, idiomatic C implementation that shows the callback-style iteration and a small usage example.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node { void *data; struct Node *next; } Node;
typedef struct { Node *front, *rear; size_t size; } Queue;

Queue* queue_create(void) {
  Queue *q = malloc(sizeof *q);
  if (!q) return NULL;
  q->front = q->rear = NULL; q->size = 0; return q;
}

int queue_enqueue(Queue *q, void *data) {
  Node *n = malloc(sizeof *n); if (!n) return 0;
  n->data = data; n->next = NULL;
  if (q->rear) q->rear->next = n; else q->front = n;
  q->rear = n; q->size++; return 1;
}

void* queue_dequeue(Queue *q) {
  if (!q->front) return NULL;
  Node *n = q->front; void *d = n->data;
  q->front = n->next; if (!q->front) q->rear = NULL;
  free(n); q->size--; return d;
}

void queue_foreach(Queue *q, void (*fn)(void *data, void *ctx), void *ctx) {
  for (Node *p = q->front; p; p = p->next) fn(p->data, ctx);
}

void queue_destroy(Queue *q, void (*free_data)(void *)) {
  while (q->front) {
    Node *n = q->front; q->front = n->next;
    if (free_data) free_data(n->data);
    free(n);
  }
  free(q);
}

/* usage */
void print_item(void *d, void *ctx) { (void)ctx; printf("%s\n", (char*)d); }
int main(void) {
  Queue *q = queue_create();
  queue_enqueue(q, strdup("one")); queue_enqueue(q, strdup("two"));
  queue_foreach(q, print_item, NULL);
  queue_destroy(q, free);
  return 0;
}

Notes: queue_enqueue returns 0 on allocation failure. Ownership of element data is kept with the caller; pass free (or NULL) to queue_destroy to free elements. Do not modify the queue structure inside the foreach callback unless the callback is written to handle node removal safely; if removals are required, either collect pointers to remove after the walk or implement a proper iterator that allows safe in-place removal. For multi-threaded use add synchronization around all operations.

Recommended Answers

All 2 Replies

Yes, If you prove that you are willing to learn.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.