You are given the head of a linked list of even length containing integers.
Each odd-indexed node contains an odd integer and each even-indexed node contains an even integer.
We call each even-indexed node and its next node a pair , e.g., the nodes with indices 0 and 1 are a pair, the nodes with indices 2 and 3 are a pair, and so on.
For every pair , we compare the values of the nodes in the pair:
If the odd-indexed node is higher, the "Odd" team gets a point.
If the even-indexed node is higher, the "Even" team gets a point.
Return the name of the team with thehigher points, if the points are equal, return"Tie".
Input: head =[2,1]Output: "Even"Explanation: There is only one pair inthis linked list and that is`(2,1)`. Since `2 > 1`, the Even team gets the point.Hence, the answer would be `"Even"`.
Example 2:
1
2
3
4
5
6
7
8
9
10
Input: head =[2,5,4,7,20,5]Output: "Odd"Explanation: There are `3` pairs inthis linked list. Let's investigate
each pair individually:`(2,5)`-> Since `2 < 5`, The Odd team gets the point.`(4,7)`-> Since `4 < 7`, The Odd team gets the point.`(20,5)`-> Since `20 > 5`, The Even team gets the point.The Odd team earned `2` points while the Even team got `1` point and the Odd
team has the higher points.Hence, the answer would be `"Odd"`.
Example 3:
1
2
3
4
5
6
7
8
Input: head =[4,5,2,1]Output: "Tie"Explanation: There are `2` pairs inthis linked list. Let's investigate
each pair individually:`(4,5)`-> Since `4 < 5`, the Odd team gets the point.`(2,1)`-> Since `2 > 1`, the Even team gets the point.Both teams earned `1` point.Hence, the answer would be `"Tie"`.
Constraints:
The number of nodes in the list is in the range [2, 100].
We traverse the linked list in pairs, comparing each even-indexed node with its next (odd-indexed) node, and tally points for “Even” and “Odd” teams. The result is based on which team has more points.
classListNode(var `val`: Int) {
var next: ListNode? = null}
classSolution {
fungameResult(head: ListNode?): String {
var even = 0var odd = 0var node = head
while (node !=null&& node.next !=null) {
if (node.`val` > node.next!!.`val`) even++elseif (node.`val` < node.next!!.`val`) odd++ node = node.next!!.next
}
returnwhen {
even > odd ->"Even" odd > even ->"Odd"else->"Tie" }
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from typing import Optional
classListNode:
def__init__(self, val: int =0, next: 'Optional[ListNode]'=None):
self.val = val
self.next = next
classSolution:
defgameResult(self, head: Optional[ListNode]) -> str:
even = odd =0while head and head.next:
if head.val > head.next.val:
even +=1elif head.val < head.next.val:
odd +=1 head = head.next.next
if even > odd:
return"Even"if odd > even:
return"Odd"return"Tie"