07-27-2023, 08:58 AM
I need to create an array of linked lists (as pictured) and this is what I've made so far:
[![enter image description here][1]][1]
[1]:
typedef struct Node {
int data;
struct Node *next;
} Node;
int main(void) {
Node* link[5];
for(int q = 0; q < 5; q++) {
link[q] = malloc(sizeof(struct Node));
link[q] = NULL;
}
}
It's been awhile since I've used linked lists in C, so I've forgotten a lot of the syntax and I'm having trouble visualizing what exactly happens when I code linked lists. If I'm not mistaken, when I call malloc in my code, I'm creating a Node with nothing in it yet?
I want to initialize it to point to NULL. And I did this with
link[q] = NULL;
Am I right in saying this is what it looks like in memory?
|1| -> NULL
|2| -> NULL
|3| -> NULL
---
My next problem would be inserting data into the linked list.
(Referring to the picture): If I want to insert another element into say the 3rd index of the array ([3]-> d -> NULL)
Would this be correct?
Node* newNode = link[3];
newNode->data = 1;
link[3] = newNode;
Thank you for the help!
[![enter image description here][1]][1]
[1]:
typedef struct Node {
int data;
struct Node *next;
} Node;
int main(void) {
Node* link[5];
for(int q = 0; q < 5; q++) {
link[q] = malloc(sizeof(struct Node));
link[q] = NULL;
}
}
It's been awhile since I've used linked lists in C, so I've forgotten a lot of the syntax and I'm having trouble visualizing what exactly happens when I code linked lists. If I'm not mistaken, when I call malloc in my code, I'm creating a Node with nothing in it yet?
I want to initialize it to point to NULL. And I did this with
link[q] = NULL;
Am I right in saying this is what it looks like in memory?
|1| -> NULL
|2| -> NULL
|3| -> NULL
---
My next problem would be inserting data into the linked list.
(Referring to the picture): If I want to insert another element into say the 3rd index of the array ([3]-> d -> NULL)
Would this be correct?
Node* newNode = link[3];
newNode->data = 1;
link[3] = newNode;
Thank you for the help!