# C program to create Even and Odd lists from a Singly linked list

Here, we are going to learn how to create Even and Odd lists from a Singly linked list using C program?
Submitted by Nidhi, on August 23, 2021

Problem Solution:

Given a singly linked list, we have to create Even and Odd lists.

Program:

The source code to create an Even and Odd lists from a Singly linked list is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

```// C program to create Even and Odd lists
// from a Singly linked list

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

//Self-referential structure to create the node.
typedef struct tmp {
int item;
struct tmp* next;
} Node;

typedef struct
{
Node* tail;

} List;

//Initialize List
void initList(List* lp)
{
lp->tail = NULL;
}

//Create node and return the reference of it.
Node* createNode(int item)
{
Node* nNode;

nNode = (Node*)malloc(sizeof(Node));

nNode->item = item;
nNode->next = NULL;

return nNode;
}

//Add a new item at the end of the list.
{
Node* node;
node = createNode(item);

//if list is empty.
lp->tail = node;
}
else {
lp->tail->next = node;
lp->tail = lp->tail->next;
}
}

//Add a new item at the beginning of the list.
{
Node* node;
node = createNode(item);

//if list is empty.
lp->tail = node;
}
else {
}
}

//To print the list from start to end of the list.
void printList(List* lp)
{
Node* node;

printf("\nEmpty List");
return;
}

while (node != NULL) {
printf("| %05d |", node->item);
node = node->next;

if (node != NULL)
printf("--->");
}
printf("\n\n");
}

void createEvenOddList(List* lp, List* lpEven, List* lpOdd)
{
Node* temp;

while (temp != NULL) {
if (temp->item % 2 == 0)
else

temp = temp->next;
}
}

//Main function to execute program.
int main()
{
List* lp;
List* lpEven;
List* lpOdd;

lp = (List*)malloc(sizeof(List));
lpEven = (List*)malloc(sizeof(List));
lpOdd = (List*)malloc(sizeof(List));

initList(lp);
initList(lpEven);
initList(lpOdd);

createEvenOddList(lp, lpEven, lpOdd);

printf("List:\n");
printList(lp);

printf("Even List:\n");
printList(lpEven);

printf("Odd List:\n");
printList(lpOdd);

return 0;
}
```

Output:

```List:
| 00101 |--->| 00102 |--->| 00103 |--->| 00104 |--->| 00105 |

Even List:
| 00102 |--->| 00104 |

Odd List:
| 00101 |--->| 00103 |--->| 00105 |
```

Explanation:

Here, we created a self-referential structure to implement a linked list, a function to add a node at the start and end of the list, a function createEvenOddList() to create separate even and odd lists from the created list.

In the main() function, we created a linked list. Then we created two separate lists for even and odd elements from the created linked list. After that, we printed all lists on the console screen.

Preparation

What's New

Top Interview Coding Problems/Challenges!