This is a debugging question. Please write comments where it is fixed. Thanks.
q7.4 Fix the errors in the code (in C)
//This program is supposed to scan 5 ints from the user
//Using those 5 ints, it should construct a linked list of 5 elements
//Then it prints the elements of the list using the PrintList function
#include <stdio.h>
struct Node{
int data;
Node* next;
};
int main(void){
struct Node first = {0, 0};
struct Node* second = {0, 0};
Node third = {0, 0};
struct Node fourth = {0, 0};
struct Node fifth = {0, &first};
int i;
scanf(" %d", &i);
first.data = i;
scanf(" %d", &i);
second.data = i
first.next = &second;
scanf(" %d", &i);
third.data = i;
second.next = third;
scanf(" %d", &i);
data = i;
third.next = &fourth;
scanf(" %d", &i);
fifth.data = i;
fourth->next = &fifth;
PrintList(first);
}
PrintList(struct Node* n){
while(n != 0){
printf("%d ", n.data);
n = n.next;
}
printf("\n");
}
Fixed all the errors, the code is working fine now.
//This program is supposed to scan 5 ints from the user
//Using those 5 ints, it should construct a linked list of 5 elements
//Then it prints the elements of the list using the PrintList function
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next; // fixed the error here by adding 'struct'
};
// Moved PrintList upwards to prevent any conflicts/warnings
void PrintList(struct Node* n){
while(n != NULL){
printf("%d ", n->data); // Changed n.data to n->data
n = n->next; //Changed n.next to n->next
}
printf("\n");
}
int main(void){
// Initialised the nodes to avoid incompatible pointer type
error
struct Node* first;
first = (struct Node *) malloc( sizeof(struct Node) );
struct Node* second;
second = (struct Node *) malloc( sizeof(struct Node) );
struct Node* third;
third = (struct Node *) malloc( sizeof(struct Node) );
struct Node* fourth;
fourth = (struct Node *) malloc( sizeof(struct Node) );
struct Node* fifth;
fifth = (struct Node *) malloc( sizeof(struct Node) );
int i=0;
// Syntax node->data = i is used because node is a pointer
here
// Syntax node->next = nextnode is used to assign the next node
in the linked list
scanf("%d", &i);
first->data = i;
scanf("%d", &i);
second->data = i;
first->next = second;
scanf(" %d", &i);
third->data = i;
second->next = third;
scanf(" %d", &i);
fourth->data = i;
third->next = fourth;
scanf(" %d", &i);
fifth->data = i;
fourth->next = fifth;
PrintList(first);
}
Get Answers For Free
Most questions answered within 1 hours.