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>
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* newNode(int data) {
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
struct Node* odd_Even_List(struct Node* head) {
if (!head) return head;
struct Node *odd = head, *even = head->next, *even_Head = even;
while (even && even->next) {
odd->next = even->next;
odd = odd->next;
even->next = odd->next;
even = even->next;
}
odd->next = even_Head;
return head;
}
// Function to print a linked list
void displayList(struct Node* head) {
while (head) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
struct Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
head->next->next->next->next->next = newNode(6);
printf("Original Singly List:\n");
displayList(head);
struct Node* result;
result = odd_Even_List(head);
printf("\nReorder the said linked list placing all even-numbered \nnodes ahead of all odd-numbered nodes:\n");
displayList(result);
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:
Previous: Combine k sorted linked lists into a single sorted linked list.
Next: Reverse a singly linked list in pairs.
What is the difficulty level of this exercise?
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join