Insert at the Front
Completed
Read n integers, inserting each at the front of a linked list. Print the list values separated by spaces (they come out reversed) and the length.
Input
Line 1: n. Line 2: n integers.
Output
Two lines.
Example
Input
4 1 2 3 4
Output
4 3 2 1 4
Editor
C
Hints
The new node's next is the old head; the new node becomes the head.
Solution explanation
Inserting at the front is O(1) - no traversal needed.
Show solution
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
};
struct Node *push_front(struct Node *head, int value) {
struct Node *node = malloc(sizeof(struct Node));
node->value = value;
node->next = head;
return node;
}
int main() {
int n, x, length = 0;
struct Node *head = NULL;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
head = push_front(head, x);
}
for (struct Node *p = head; p != NULL; p = p->next) {
printf("%d ", p->value);
length++;
}
printf("\n%d\n", length);
return 0;
}