Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
C# Program For Deleting A Node In A Doubly Linked List
Next article icon

C Program For Segregating Even And Odd Nodes In A Linked List

Last Updated : 28 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers the same.

Examples: 

Input: 17->15->8->12->10->5->4->1->7->6->NULL Output: 8->12->10->4->6->17->15->5->1->7->NULL  Input: 8->12->10->5->4->1->6->NULL Output: 8->12->10->4->6->5->1->NULL  // If all numbers are even then do not change the list Input: 8->12->10->NULL Output: 8->12->10->NULL  // If all numbers are odd then do not change the list Input: 1->3->5->7->NULL Output: 1->3->5->7->NULL
Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.

Method: 
The idea is to get pointer to the last node of list. And then traverse the list starting from the head node and move the odd-valued nodes from their current position to end of the list.
Thanks to blunderboy for suggesting this method. Algorithm: 

  1. Get pointer to the last node.
  2. Move all the odd nodes to the end.
    • Consider all odd nodes before the first even node and move them to end.
    • Change the head pointer to point to the first even node.
    • Consider all odd nodes after the first even node and move them to the end. 

Below is the implementation of the above approach:

C
// C program to segregate even and  // odd nodes in a Linked List #include <stdio.h> #include <stdlib.h>  // A node of the singly linked list  struct Node {     int data;     struct Node *next; };  void segregateEvenOdd(struct Node **head_ref) {     struct Node *end = *head_ref;     struct Node *prev = NULL;     struct Node *curr = *head_ref;      // Get pointer to the last node      while (end->next != NULL)         end = end->next;      struct Node *new_end = end;      /* Consider all odd nodes before the         first even node and move then after         end */     while (curr->data % 2 != 0 &&             curr != end)     {         new_end->next = curr;         curr = curr->next;         new_end->next->next = NULL;         new_end = new_end->next;     }      // 10->8->17->17->15     /* Do following steps only if there         is any even node */     if (curr->data % 2 == 0)     {         /* Change the head pointer to point             to first even node */         *head_ref = curr;          /* Now current points to the first             even node */         while (curr != end)         {             if ( (curr->data) % 2 == 0 )             {                 prev = curr;                 curr = curr->next;             }             else             {                 /* Break the link between prev                     and current */                 prev->next = curr->next;                  // Make next of curr as NULL                   curr->next = NULL;                  // Move curr to end                  new_end->next = curr;                  // Make curr as new end of list                  new_end = curr;                  /* Update current pointer to next                     of the moved node */                 curr = prev->next;             }         }     }      /* We must have prev set before executing         lines following this statement */     else prev = curr;      /* If there are more than 1 odd nodes and         end of original list is odd then move         this node to end to maintain same order         of odd numbers in modified list */     if (new_end != end &&         (end->data) % 2 != 0)     {         prev->next = end->next;         end->next = NULL;         new_end->next = end;     }     return; }  // UTILITY FUNCTIONS  /* Function to insert a node at     the beginning  */ void push(struct Node** head_ref,            int new_data) {     // Allocate node      struct Node* new_node =            (struct Node*) malloc(sizeof(struct Node));      // Put in the data       new_node->data = new_data;      // Link the old list off the new node      new_node->next = (*head_ref);      // Move the head to point to the new node      (*head_ref) = new_node; }  // Function to print nodes in  // a given linked list  void printList(struct Node *node) {     while (node!=NULL)     {         printf("%d ", node->data);         node = node->next;     } }  // Driver code int main() {     // Start with the empty list      struct Node* head = NULL;      /* Let us create a sample linked list         as following 0->2->4->6->8->10->11 */     push(&head, 11);     push(&head, 10);     push(&head, 8);     push(&head, 6);     push(&head, 4);     push(&head, 2);     push(&head, 0);      printf("Original Linked list ");     printList(head);      segregateEvenOdd(&head);      printf("Modified Linked list ");     printList(head);      return 0; } 

Output
Original Linked list 0 2 4 6 8 10 11 Modified Linked list 0 2 4 6 8 10 11 

Time complexity: O(n)
Auxiliary space: O(1) as it is using constant space


Please refer complete article on Segregate even and odd nodes in a Linked List for more details!


Next Article
C# Program For Deleting A Node In A Doubly Linked List
author
kartik
Improve
Article Tags :
  • Linked List
  • C Programs
  • C Language
  • DSA
  • Linked Lists
  • Amazon
Practice Tags :
  • Amazon
  • Linked List

Similar Reads

  • C Program For Searching An Element In A Linked List
    Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then functi
    4 min read
  • C Program For Deleting A Node In A Doubly Linked List
    Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list
    4 min read
  • C# Program For Deleting A Node In A Doubly Linked List
    Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List  Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list
    4 min read
  • C Program For Sorting A Linked List Of 0s, 1s And 2s
    Given a linked list of 0s, 1s and 2s, sort it.Examples: Input: 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> NULL Output: 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2 -> NULL Input: 1 -> 1 -> 2 -> 1 -> 0 -> NULL Output: 0 -> 1 -> 1 -> 1 -> 2 -> NULL So
    3 min read
  • C Program For Writing A Function To Get Nth Node In A Linked List
    Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->30->14, index = 2 Output: 30 The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, before moving on to th
    2 min read
  • C Program For Deleting A Linked List Node At A Given Position
    Given a singly linked list and a position, delete a linked list node at the given position. Example: Input: position = 1, Linked List = 8->2->3->1->7 Output: Linked List = 8->3->1->7 Input: position = 0, Linked List = 8->2->3->1->7 Output: Linked List = 2->3->1
    3 min read
  • C Program For Writing A Function To Delete A Linked List
    Algorithm For C:Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted. Implementation: C/C++ Code // C program to delete a linked list #include<stdio.h> #include<stdlib.h
    2 min read
  • C# Program For Writing A Function To Get Nth Node In A Linked List
    Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->30->14, index = 2 Output: 30 The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, before moving on to th
    4 min read
  • C Program To Delete Alternate Nodes Of A Linked List
    Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3. Recomm
    3 min read
  • C Program For Pairwise Swapping Elements Of A Given Linked List
    Given a singly linked list, write a function to swap elements pairwise. Input: 1->2->3->4->5->6->NULL Output: 2->1->4->3->6->5->NULL Input: 1->2->3->4->5->NULL Output: 2->1->4->3->5->NULL Input: 1->NULL Output: 1->NULL For examp
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences