I've been trying to insert a node into a list using the "void push()"-function, but I can't really get it to work. Basically what I want this to do is for it to insert every new node created from (typedef struct node) to the head of the list (typedef struct list) and to be able to display it. I'm pretty new to C and for now I'm most familiar with using stdio.h and stdlib.h.
This is my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
struct node *prev;
}N;
typedef struct list
{
N *head;
}L;
void push(N** headloc, int newdata)
{
N *newnode = (N*)malloc(sizeof(N));
newnode->data= newdata;
newnode->next = (*headloc);
newnode->prev = NULL;
if((*headloc) != NULL)
(*headloc)->prev = newnode;
(*headloc) = newnode;
(*headloc)->prev = NULL;
}
void printlist(N *n)
{
printf("Linked list: ");
N *last;
while (n != NULL)
{
printf("%d ", n->data);
last = n;
n = n->next;
}
}
int main()
{
N *head = NULL;
push(&head, 2);
printlist(head);
}
CodePudding user response:
First of all, the code you have is working (but is leaking memory). In order to store the nodes in a struct list
(or L
as you've typedef
ined it), you need to make your push
and printlist
functions take a pointer to an L
instead.
Example:
void push(L *l, int newdata) { // An `L` pointer
N *newnode = malloc(sizeof *newnode);
newnode->data = newdata;
newnode->next = l->head; // use `L`s head
newnode->prev = NULL;
// again, use l->head below:
if (l->head) l->head->prev = newnode;
l->head = newnode;
// (*headloc)->prev = NULL; // newnode->prev is already NULL
}
// A helper function to create and initialize a new list
L *list_create() {
return calloc(1, sizeof(L));
}
void printlist(L *l) { // L pointer again
N *n = l->head; // and use its head
printf("Linked list: ");
// N *last; // unused, remove
while (n) {
printf("%d ", n->data);
n = n->next;
}
putchar('\n');
}
// free resources when you're done with the list
void freelist(L *l) {
for(N *n = l->head, *nn; n; n = nn) {
nn = n->next;
free(n);
}
free(l);
}
You can then create multiple separate lists and populate them as you wish:
int main() {
L *l1 = list_create();
L *l2 = list_create();
push(l1, 2);
push(l2, 3);
push(l1, 4);
push(l2, 5);
printlist(l1); // pushed 2 4
printlist(l2); // pushed 3 5
freelist(l1);
freelist(l2);
}
Output:
Linked list: 4 2
Linked list: 5 3