Search code examples
cstructstackmaze

Is it possible to store a struct into a linked list?


I'm writing a program that solves a maze using DFS algorithm and stack. I was thinking of storing the coordinates of the path used to get to the end onto a struct containing integers x,y for coordinates and then pushing that struct onto a stack to perform other instructions on (print, pop, etc.).

I have searched all over and have yet to find anything that helps. So I went ahead and set it up but I'm getting an error about type compatibility since I have my node data as an int but I'm trying to put in a struct. Being new to linked lists I have only seen data as an int or char. Finally, is it even possible to do what I want? If not could you suggest a way of passing both x,y coordinates onto the stack? Thank you in advance.

Here's a sample of my code, where to save space a1 is an instance of COORD, and list is initialized as well as the maze and such.

typedef struct node {
    int data;           /* Value or data stored in node*/
    struct node *pNext; /* Reference to the next node address */
} NODE;

/*Structure declares pointers for front and back of the list*/
    typedef struct LIST {
    NODE *front;
    NODE *back;
} LIST;

/* Structure to pass multiple values onto stack */
typedef struct COORD{
    int x;
    int y;
}COORD;

/*Example of one of the functions */
void lst_push_front(LIST *l, COORD *a1) {
    NODE *p = malloc(sizeof(NODE));

    p->data = a1;
    p->pNext = l->front;

    l->front = p;
    if(l->back == NULL)   // was empty, now one elem
       l->back = p;
}

Solution

  • Check the code below.

    Since COORD is a structure you can include it in another structure as shown in the below code.

    Also make sure that the ordering of the structures are proper. p->data.x is the right way to access the members of the structure COORD

    #include <stdio.h>
    
    /* Structure to pass multiple values onto stack */
    typedef struct COORD{
        int x;
        int y;
    }COORD;
    
     typedef struct node {
        COORD data;           /*  --> Changes done here */
        struct node *pNext; /* Reference to the next node address */
    } NODE;
    
    /*Structure declares pointers for front and back of the list*/
        typedef struct LIST {
        NODE *front;
        NODE *back;
    } LIST;
    
    
    void func(COORD *q)
    {
        NODE *p = malloc(sizeof(NODE));
        p->data.x = q->x;
        p->data.y = q->y;
    
        printf("%d %d",p->data.x,p->data.y);
        free(p);
    }
    
    int main(void) {
    
        COORD *q = malloc(sizeof(COORD));
        q->x = 20;
        q->y = 30;
        func(q);
        free(q);
        return 0;
    }