List Mixed
Difficulty: ⚫⚫◯◯
Tags: linked-list, traversal, even-odd
Hurdle: Passing this question is sufficient to pass the linked lists hurdle.
Description
Write a function mixed that is given one argument: head, a pointer to the first node of a linked list.
The function should return:
1if the linked list contains both even and odd numbers0otherwise
Examples
Example 1: Contains Both
List: 16 -> 12 -> 8 -> 3 -> 6 -> 12 -> X
Output: 1
Explanation: The list contains 3 (odd) and 16, 12, 8, 6, 12 (even). Since it has both, return 1.
Example 2: Only Even
List: 16 -> 12 -> 8 -> 6 -> 12 -> X
Output: 0
Explanation: The list contains only even numbers, so return 0.
Example 3: Only Odd
List: 3 -> 1 -> X
Output: 0
Explanation: The list contains only odd numbers (3, 1), so return 0.
Example 4: Mixed
List: 3 -> 1 -> 4 -> X
Output: 1
Explanation: Contains 3, 1 (odd) and 4 (even), so return 1.
Example 5: Mixed
List: 1 -> 2 -> 3 -> 4 -> X
Output: 1
Explanation: Contains both odd (1, 3) and even (2, 4) numbers.
Example 6: Single Element
List: 42 -> X
Output: 0
Explanation: Only one even number, no odd numbers present.
Example 7: Empty List
List: (empty)
Output: 0
Explanation: Empty list has neither even nor odd numbers.
Function Signature
int mixed(struct node *head);
Data Structure
struct node {
struct node *next;
int data;
};
Constraints
- Return only
1or0. - Do not change the linked list provided.
- Do not change the
nextordatafields of list nodes. - Do not use arrays.
- Do not call
malloc. - Do not call
scanf,getchar, orfgets. - Do not call
printf.
Hints
- Use two flags: one to track if you've seen an even number, one for odd.
- A number is even if
data % 2 == 0, odd otherwise. - Return 1 only if both flags are set.
Testing
./list-mixed 3 1 4
1
./list-mixed 3 1
0
./list-mixed 2 4 6 42
0
./list-mixed 1 2 3 4
1
./list-mixed 42
0
./list-mixed
0
./list-mixed 16 12 8 3 6 12
1
./list-mixed 16 12 8 6 12
0