Here is one way to code a singly linked list in C:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* n) {
while (n != NULL) {
printf(" %d ", n->data);
n = n->next;
}
}
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main() {
struct Node* head = NULL;
push(&head, 1);
push(&head, 2);
push(&head, 3);
printList(head);
return 0;
}
The key steps are:
- Define a Node structure with an integer data field and a pointer next to another node
- push() allocates a new node, sets its data field, and inserts it at the head of the list by updating the head pointer
- printList() iterates through the list starting from the head and prints each node's data
To implement a doubly linked list, each node would also need a prev pointer, and extra logic to maintain backwards links.