AI Generated Question Papers

Problem_Solving_C_ESA.pdf

Answer Key 1.pdf

Problem_Solving_C_ESA_Set2.pdf

Answer Key 2.pdf

Linked List Code:

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

// Define the structure for a linked list node
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 1. CREATING: Allocate memory for a new node
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (newNode == NULL) {
        printf("Memory allocation failed!\n");
        exit(1);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 2. ADDING TO FRONT: Insert a new node at the beginning of the list
void insertFront(Node** head, int data) {
    Node* newNode = createNode(data);
    newNode->next = *head; // Point new node to the current head
    *head = newNode;       // Update head to be the new node
    printf("Inserted %d at the front.\n", data);
}

// 3. ADDING TO BACK: Insert a new node at the end of the list
void insertBack(Node** head, int data) {
    Node* newNode = createNode(data);
    
    // If the list is empty, the new node becomes the head
    if (*head == NULL) {
        *head = newNode;
        printf("Inserted %d at the back.\n", data);
        return;
    }
    
    // Otherwise, traverse to the last node
    Node* temp = *head;
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp->next = newNode; // Link the last node to the new node
    printf("Inserted %d at the back.\n", data);
}

// 4. DELETING FROM FRONT: Remove the first node in the list
void deleteFront(Node** head) {
    if (*head == NULL) {
        printf("List is empty, nothing to delete.\n");
        return;
    }
    
    Node* temp = *head;       // Store the current head
    *head = (*head)->next;    // Move head pointer to the next node
    printf("Deleted %d from the front.\n", temp->data);
    free(temp);               // Free the memory
}

// 5. DELETING FROM BACK: Remove the last node in the list

// Helper function to print the list
void printList(Node* head) {
    printf("Current List: ");
    Node* temp = head;
    while (temp != NULL) {
        printf("%d -> ", temp->data);
        temp = temp->next;
    }
    printf("NULL\n\n");
}

int main() {
    Node* head = NULL; // Initialize an empty list

    insertFront(&head, 10);
    insertFront(&head, 20);
    printList(head);

    deleteFront(&head);
    printList(head);

    deleteBack(&head);
    printList(head);

    return 0;
}