Salta al contenuto
Note per Studenti Stacks and Queues in C Report

Stacks and Queues in C

In questa pagina 8

Both are linear structures obtained from a list by restricting where insertions and deletions happen (see Linked Lists in CA linked list is a chain of dynamically allocated nodes, each holding data and a pointer to the next one; insertion and deletion only relink pointers, but access is sequential.Linked Lists in C →).

Stack

LIFO (Last In First Out): the last element inserted comes out first. Insertion and removal happen at the same end, the top. Only the top is accessible, so the implementation keeps a pointer/index to the top. Real-life example: plates stacked in a canteen.

Operation Meaning
push() insert an element; on a full stack: overflow
pop() remove the top element (items come out in reverse push order); on an empty stack: underflow
top() return the top element without removing it
isEmpty() true if the stack is empty
isFull() true if the stack is full (fixed size only)
size() number of elements

All of these take O(1) time.

Types:

  • Fixed size stack: cannot grow or shrink; overflow/underflow errors.
  • Dynamic size stack: grows and shrinks; implemented with a linked list.

Stack on an array

Array version: push = increment the top index and store; pop = return the element at the top index and decrement it.

c
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// A structure to represent a stack
struct Stack {
    int top;
    unsigned int capacity;
    int* array;
};

// create a stack of given capacity; top = -1 means empty
struct Stack* createStack(unsigned int capacity)
{
    struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
    stack->capacity = capacity;
    stack->top = -1;
    stack->array = (int*)malloc(stack->capacity * sizeof(int));
    return stack;
}

// Stack is full when top is equal to the last index
bool isFull(struct Stack* stack)
{
    return(stack->top == stack->capacity - 1);
}
// Stack is empty when top is equal to -1
bool isEmpty(struct Stack* stack)
{
    return(stack->top == -1);
}

// Add an item to the stack. It increases top by 1
int push(struct Stack* stack, int item)
{
    if (isFull(stack))
        return(-1);
    stack->array[++stack->top] = item;
    printf("%d pushed to stack\n", item);
    return(0);
}

// Remove an item from the stack. It decreases top by 1
int pop(struct Stack* stack)
{
    if (isEmpty(stack))
        return(INT_MIN);
    return stack->array[stack->top--];
}

// Return the top without removing it
int top(struct Stack* stack)
{
    if (isEmpty(stack))
        return(INT_MIN);
    return stack->array[stack->top];
}

// Program to test the functions
int main()
{
    struct Stack* stack = createStack(100);
    push(stack, 10);
    push(stack, 25);
    push(stack, 5);
    push(stack, 15);
    printf("%d popped from stack\n", pop(stack));
    printf("%d at the top of the stack\n", top(stack));
    return(0);
}

Notes: INT_MIN (from <limits.h>) is the error value of pop/top on an empty stack; push returns -1 when full, 0 on success. bool needs <stdbool.h> (not shown on the slides); the slide prints the minus in capacity - 1 with a typographic dash that does not compile.

  • Pros: easy to implement; memory saved (no pointers).
  • Cons: not dynamic; total size fixed beforehand.

Stack on a linked list

Push = new node whose next is the current top, top points to it. Pop = top moves to top->next, return the old value (and free the node).

c
struct StackNode {
    int data;
    struct StackNode* next;
};

int isEmpty(struct StackNode* head)
{
    return(!head);
}

void push(struct StackNode** head, struct StackNode* newNode)
{
    newNode->next = *head;
    *head = newNode;
    printf("%d pushed to stack\n", newNode->data);
}

int pop(struct StackNode** head)
{
    if (isEmpty(*head))
        return(INT_MIN);
    struct StackNode* tmp = *head;
    *head = (*head)->next;
    int popped = tmp->data;
    free(tmp);
    return(popped);
}

int top(struct StackNode* head)
{
    if (isEmpty(head))
        return(INT_MIN);
    return(head->data);
}

push is exactly head insertion in a list, pop is head deletion. The node is created by the caller (createNode, as in Linked Lists in CA linked list is a chain of dynamically allocated nodes, each holding data and a pointer to the next one; insertion and deletion only relink pointers, but access is sequential.Linked Lists in C →).

  • Pros: grows and shrinks at run time; used in many virtual machines such as the JVM.
  • Cons: extra memory for pointers; no random access.

Exercise: reverse a string (slide)

Read a sequence of characters and print them in reverse order using a stack managed by a linked list. Example: easy exercise -> esicrexe ysae. Suggested functions: listInizialization, createNode, push, push. No solution on the slides; see Lab Exercises - Lists, Arrays and TreesLab problem sets on linked lists, stacks, queues, arrays and binary search trees, with the statements, the data declarations and program skeletons given on the slides, plus the quiz questions.Lab Exercises - Lists, Arrays and Trees →.

Monotonic stack

A stack whose elements, from bottom to top, are all increasing or all decreasing; it has all the properties of a normal stack. It keeps monotonicity by popping elements when a new item is pushed.

  • Monotonic increasing: 1, 3, 10, 15, 17
  • Monotonic decreasing: 17, 14, 10, 5, 1

Queue

FIFO (First In First Out): a list where all additions are made at one end and all deletions at the other. Like a line at the ticket office. The front (head) is the first entry, the next one to be removed; the rear (tail) is the last, most recently added.

Operations: enqueue (add at the rear), dequeue (remove from the front), front() and rear() (look without removing), isEmpty, isFull.

Queue on an array (circular)

Variables: the array, front (index of the first element), rear (index of the last one). The indexes wrap around with %, so the array is used as a circle.

c
// A structure to represent a queue
struct Queue {
    int front, rear, size;
    unsigned int capacity;
    int* array;
};

// create a queue of given capacity, size 0
struct Queue* createQueue(unsigned int capacity)
{
    struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
    queue->capacity = capacity;
    queue->front = queue->size = 0;
    queue->rear = queue->front - 1;
    queue->array = (int*)malloc(queue->capacity * sizeof(int));
    return(queue);
}

// Queue is full when size becomes equal to the capacity
int isFull(struct Queue* queue)
{
    return (queue->size == queue->capacity);
}
// Queue is empty when size is 0
int isEmpty(struct Queue* queue)
{
    return (queue->size == 0);
}

enqueue steps: check if full (overflow error); otherwise advance rear to the next empty slot, store the data, return success.

c
int enqueue(struct Queue* queue, int item)
{
    if (isFull(queue))
        return(-1);
    queue->rear = (queue->rear + 1) % queue->capacity;
    queue->array[queue->rear] = item;
    queue->size = queue->size + 1;
    printf("%d enqueued to queue\n", item);
    return(0);
}

dequeue steps: check if empty (underflow error); otherwise read the data at front, advance front, return success.

c
int dequeue(struct Queue* queue)
{
    if (isEmpty(queue)) {
        printf("\nQueue is empty\n");
        return(INT_MIN);
    }
    int item = queue->array[queue->front];
    queue->front = (queue->front + 1) % queue->capacity;
    queue->size = queue->size - 1;
    return (item);
}
c
int front(struct Queue* queue)
{
    if (isempty(queue))          // as on the slide
        return(INT_MIN);
    return (queue->arr[queue->front]);   // as on the slide
}

int rear(struct Queue* queue)
{
    if (isEmpty(queue))
        return(INT_MIN);
    return (queue->array[queue->rear]);
}

The slide's front() has typos (isempty, queue->arr): the names must be isEmpty and queue->array, as in rear().

c
int main()
{
    struct Queue* queue = createQueue(1000);
    enqueue(queue, 16);
    enqueue(queue, 22);
    enqueue(queue, 30);
    enqueue(queue, 13);
    printf("%d dequeued from queue\n", dequeue(queue));
    printf("Front item is %d\n", front(queue));
    printf("Rear item is %d\n", rear(queue));
    return 0;
}

Queue on a linked list

Entities: linked list, pointers, structures. The queue keeps two pointers: the front node and the rear node, so enqueue at the tail does not need a traversal.

c
// A linked list (LL) node to store a queue entry
struct QNode {
    int data;
    struct QNode* next;
};

/* The queue: front stores the front node and rear stores the last node of LL */
struct Queue {
    struct QNode *front, *rear;
};

// A utility function to create a new LL node.
struct QNode* newNode(int k) {
    struct QNode* tmp = (struct QNode*)malloc(sizeof(struct QNode));
    if (tmp != NULL) {
        tmp->data = k;
        tmp->next = NULL;
    }
    return(tmp);
}

// A utility function to create an empty queue
struct Queue* createQueue()
{
    struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
    q->front = q->rear = NULL;
    return(q);
}

// The function to add a data k to q
void enQueue(struct Queue* q, int k) {
    // Create a new LL node
    struct QNode* tmp = newNode(k);
    if (tmp != NULL) {
        // If queue is empty, then new node is front and rear both
        if (q->rear == NULL)
            q->front = q->rear = tmp;
        else {
            // Add the new node at the end of queue and change rear
            q->rear->next = tmp;
            q->rear = tmp;
        }
    }
}

// Function to dequeue a key from given queue q
struct QNode* deQueue(struct Queue* q) {
    // If queue is empty, return NULL.
    if (q->front == NULL)
        return(NULL);
    // Store previous front and move front one node ahead
    struct QNode* tmp = q->front;
    q->front = q->front->next;
    // If front becomes NULL, then change rear also as NULL
    if (q->front == NULL)
        q->rear = NULL;
    return(tmp);
}

Key points: when the last element is removed rear must also become NULL; deQueue returns the node (the caller reads data and must free it: the slide does not free it).

Test on the slides (empty-queue guards on the printouts):

c
int main()
{
    struct Qnode* tmp = NULL;     // slide spells it Qnode: the type is struct QNode
    struct Queue* q = createQueue();
    enQueue(q, 10);
    enQueue(q, 20);
    tmp = deQueue(q);
    tmp = deQueue(q);
    enQueue(q, 30);
    enQueue(q, 40);
    enQueue(q, 50);
    tmp = deQueue(q);
    printf("Queue Front : %d \n", ((q->front != NULL) ? (q->front)->data : -1));
    printf("Queue Rear : %d", ((q->rear != NULL) ? (q->rear)->data : -1));
    return(0);
}

Working it out: after the operations the queue holds 40, 50, so it prints front 40 and rear 50.

Exercise: read and print in order (slide)

Read a sequence of characters and print them in reading order using a queue managed by a linked list. Suggested functions: queueInizialization, createNode, enQueue, deQueue. No solution on the slides.

Stack vs queue

Stack Queue
Policy LIFO FIFO
Insert push at top enqueue at rear
Remove pop at top dequeue at front
List implementation head insert / head delete, one pointer tail insert + head delete, two pointers
Array implementation index top circular, indexes front/rear with %

Queues also drive the level-order traversal of a tree (Trees in CA tree is a set of nodes with a root and a unique predecessor per node; in C a binary search tree uses a struct with two child pointers and recursive search, insertion at a leaf, three-case deletion and four traversals.Trees in C →).

Versione ripasso

  • Stack = LIFO (last in, first out): insertion and removal both at the top, only the top is accessible. Ops: push, pop, top, isEmpty, isFull (fixed size only), size; all O(1). Overflow = push on a full stack, underflow = pop on an empty one.
  • Array stack: top = -1 means empty; full when top == capacity - 1; push: stack->array[++stack->top] = item; (returns -1 if full); pop: return stack->array[stack->top--];. Error value INT_MIN from <limits.h>. Pros: simple, no pointers; cons: fixed size fixed beforehand.
c
int pop(struct Stack* stack) {
    if (isEmpty(stack)) return INT_MIN;
    return stack->array[stack->top--];
}

Teoria collegata