Build a Linked List
Completed
Read n integers and append each to the end of a singly linked list. Print the list as 1 -> 2 -> 3 -> NULL and free every node.
Input
Line 1: n. Line 2: n integers.
Output
One line.
Example
Input
3 1 2 3
Output
1 -> 2 -> 3 -> NULL
Editor
C
Hints
Keep a tail pointer so appending doesn't have to walk the whole list.
Save next before freeing a node.
Solution explanation
Each node holds a value and a pointer to the next node; NULL marks the end.
Show solution
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
};
int main() {
int n, x;
struct Node *head = NULL;
struct Node *tail = NULL;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
struct Node *node = malloc(sizeof(struct Node));
node->value = x;
node->next = NULL;
if (head == NULL) head = node;
else tail->next = node;
tail = node;
}
struct Node *p = head;
while (p != NULL) {
printf("%d -> ", p->value);
p = p->next;
}
printf("NULL\n");
while (head != NULL) {
struct Node *next = head->next;
free(head);
head = next;
}
return 0;
}