I made a C program that is supposed to print out a linked list of integers in reverse order based on how the integers are entered. However, for some reason, the program does not print out the reverse linked list.
Here is the code I used:
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node* next;
};
struct node* create_node(int value) {
struct node* new_node = (struct node*)malloc(sizeof(struct node));
if (new_node == NULL) {
printf("Error allocating memory.\n");
exit(1);
}
new_node->value = value;
new_node->next = NULL;
return new_node;
}
void insert_node_end (struct node** head, int value) {
struct node* new_node = create_node(value);
if (*head == NULL) {
*head = new_node;
} else {
struct node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}
}
struct node* reverse_list(struct node* head) {
struct node* prev = NULL;
struct node* current = head;
struct node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
int main() {
struct node* head = NULL;
int value;
printf("Enter a list of integers. Press ctrl-d to finish.\n");
while (scanf("%d", &value) != EOF) {
insert_node_end(&head, value);
}
printf("Data entered in the list:\n");
while (head != NULL) {
printf("%d ", head->value);
head = head->next;
}
printf("\n");
head = reverse_list(head);
printf("List in reverse order:\n");
while (head != NULL) {
printf("%d ", head->value);
head = head->next;
}
printf("\n");
return 0;
}
This is what is supposed to happen:
Enter a list of integers. Press ctrl-d to finish.
7
6
5
Data entered in the list:
7 6 5
List in reverse order:
5 6 7
Except this program does not print out the list in reverse order, and instead leaves it blank, as shown below.
Enter a list of integers. Press ctrl-d to finish.
7
6
5
Data entered in the list:
7 6 5
List in reverse order:
Can you help me with this?
The main problem is that you reassign head
in your main
function so you loose track of where the list begins. After this loop, head
will be NULL
:
while (head != NULL) {
printf("%d ", head->value);
head = head->next;
}
Use a temporary variable to print out the values in both loops in main
:
for(struct node *curr = head; curr; curr = curr->next) {
printf("%d ", curr->value);
}
...or write a function to print the list and call that:
void print_list(struct node *head) {
for(; head; head = head->next) {
printf("%d ", head->value);
}
putchar('\n');
}