﻿ C Program: Reorder even-numbered before odd in a singly linked list

# C Exercises: Reorder even-numbered before odd in a singly linked list

## C Singly Linked List : Exercise-30 with Solution

Write a C program to create and reorder a linked list placing all even-numbered nodes ahead of all odd-numbered nodes.

Sample Solution:

C Code:

``````#include<stdio.h>
#include <stdlib.h>

// Structure defining a node in a singly linked list
struct Node {
int data; // Data stored in the node
struct Node* next; // Pointer to the next node
};

// Function to create a new node in the singly linked list
struct Node* newNode(int data) {
struct Node* node = (struct Node*) malloc(sizeof(struct Node)); // Allocate memory for a new node
node->data = data; // Assign data to the new node
node->next = NULL; // Initialize the next pointer as NULL
return node; // Return the new node
}

// Function to reorder a singly linked list placing all even-numbered nodes ahead of all odd-numbered nodes
struct Node* odd_Even_List(struct Node* head) {
if (!head) return head; // If the list is empty or has only one element, return the list
struct Node *odd = head, *even = head->next, *even_Head = even; // Initialize odd and even pointers
while (even && even->next) {
odd->next = even->next; // Point odd nodes to the next odd node
odd = odd->next; // Move odd pointer
even->next = odd->next; // Point even nodes to the next even node
even = even->next; // Move even pointer
}
odd->next = even_Head; // Connect the odd nodes to the even nodes
return head; // Return the reordered list
}

// Function to print a linked list
printf("%d ", head->data); // Print the data of the current node
}
printf("\n");
}

// Main function
int main() {
struct Node* head = newNode(1); // Create and populate a singly linked list
printf("Original Singly List:\n");
displayList(head); // Display the original list

struct Node* result; // Reorder the linked list placing all even-numbered nodes ahead of all odd-numbered nodes
printf("\nReorder the said linked list placing all even-numbered \nnodes ahead of all odd-numbered nodes:\n");
displayList(result); // Display the reordered list

return 0;
}
```
```

Sample Output:

```Original Singly List:
1 2 3 4 5 6

Reorder the said linked list placing all even-numbered
nodes ahead of all odd-numbered nodes:
1 3 5 2 4 6
```

Flowchart :

C Programming Code Editor:

What is the difficulty level of this exercise?

﻿