#include <stdio.h>
#include <stdlib.h>
// Node structure for doubly linked list
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
// Function to create a new node with given data
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// Function to create and initialize doubly linked list from array
Node* createDoublyLinkedList(int arr[], int size) {
if (size == 0) return NULL; // empty list
Node* head = createNode(arr[0]); // create first node
Node* curr = head;
for (int i = 1; i < size; i++) {
Node* newNode = createNode(arr[i]);
curr->next = newNode; // link current node to new node
newNode->prev = curr; // link new node back to current
curr = newNode; // move current to new node
}
return head;
}
// Function to print doubly linked list forward
void printListForward(Node* head) {
Node* curr = head;
while (curr != NULL) {
printf("%d", curr->data);
if (curr->next != NULL) printf(" ↔ ");
curr = curr->next;
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3};
int size = sizeof(arr) / sizeof(arr[0]);
Node* head = createDoublyLinkedList(arr, size);
printListForward(head);
return 0;
}
Node* head = createNode(arr[0]); // create first node
initialize head with first node
curr->next = newNode; // link current node to new node
link current node's next to new node
newNode->prev = curr; // link new node back to current
link new node's prev to current node
curr = newNode; // move current to new node
advance current pointer to new node