Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.3 kB
0
Indexable
Never
/*************************************
* Lab 1 Exercise 3
* Name: WANG HUILIN
* Student No: A0219760B
* Lab Group: T01
*************************************/

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

#include "function_pointers.h"
#include "node.h"

// The runner is empty now! Modify it to fulfill the requirements of the
// exercise. You can use ex2.c as a template

// DO NOT initialize the func_list array in this file. All initialization
// logic for func_list should go into function_pointers.c.

// Macros
#define SUM_LIST 0
#define INSERT_AT 1
#define DELETE_AT 2
#define ROTATE_LIST 3
#define REVERSE_LIST 4
#define RESET_LIST 5
#define MAP 6

void run_instruction(list *lst, int instr); 

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(stderr, "Error: expecting 1 argument, %d found\n", argc - 1);
        exit(1);
    }

    // We read in the file name provided as argument
    char *fname = argv[1];

    // Update the array of function pointers
    // DO NOT REMOVE THIS CALL
    // (You may leave the function empty if you do not need it)
    update_functions();
    FILE *fp;
    fp = freopen(fname, "r", stdin);
    list *lst = (list *)malloc(sizeof(list));
    lst->head = NULL;
    if(fp == NULL){
        return 0;
    }

    int instr;
    while (scanf("%d", &instr) != EOF) {
        run_instruction(lst, instr);
    }
    fclose(fp);
    reset_list(lst);
    free(lst);

    // Rest of code logic here
}

void run_instruction(list *lst, int instr) {
    int index, data, offset, sum;
    switch (instr) {
        case SUM_LIST:
            sum = sum_list(lst);
            printf("%d", sum);
            break;
        case INSERT_AT:
            scanf("%d %d", &index, &data);
            insert_node_at(lst, index, data);
            break;
        case DELETE_AT:
            scanf("%d", &index);
            delete_node_at(lst, index);
            break;
        case ROTATE_LIST:
            scanf("%d", &offset);
            rotate_list(lst, offset);
            break;
        case REVERSE_LIST:
            reverse_list(lst);
            break;
        case RESET_LIST:
            reset_list(lst);
            break;
        case MAP:
            scanf("%d", &index);
            map(lst, func_list[index]);
    }
}