I think I'm missing something important about pointers and memory. This is the minimum code needed:
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node* next;
};
struct node* init(int value) {
struct node* head = (struct node*)malloc(sizeof(struct node));
if (!head) return NULL;
head->value = value;
head->next = NULL;
return head;
}
void insert_back(struct node* head, int value) {
if (!head) return;
struct node* temp = head;
struct node* new = (struct node*)malloc(sizeof(struct node));
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new;
new->value = value;
new->next = NULL;
return;
}
struct node* insert_front(struct node* head, int value) {
struct node* temp;
struct node* new = (struct node*)malloc(sizeof(struct node));
new->value = value;
new->next = head;
temp = head;
head = new;
head->next = temp;
return new;
}
void insert_front_2(struct node* head, int value) {
struct node* temp;
struct node* new = (struct node*)malloc(sizeof(struct node));
new->value = value;
new->next = head;
temp = head;
head = new;
head->next = temp;
}
void print_list(struct node* head) {
if (!head) return;
struct node* temp = head;
int i = 0;
while (temp != NULL) {
printf("At position %d value %d \n", i, temp->value);
i++;
temp = temp->next;
}
}
int main() {
struct node* head = init(5);
insert_back(head, 7);
insert_back(head, 9);
insert_back(head, 12);
insert_back(head, 13);
insert_back(head, 14);
insert_back(head, 15);
head = insert_front(head, 100);
insert_front_2(head, 200);
print_list(head);
free(head);
return 1;
}
The problem concerns the function void insert_front_2(...)
. I do not understand why struct ndoe * instert_front
works perfectly, but insert_front_2
does not hold the new head once I am in the main - that is, when I print the list, the new head is not printed. Any ideas? How should I modify void insert_front_2(...)
to make it work?