[LeetCode] Winner of the Linked List Game

3062. Winner of the Linked List Game

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 the higher points, if the points are equal, return "Tie".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
string gameResult(ListNode* head) {
int res = 0;
ListNode* even = head;
ListNode* odd = even->next;


while(1) {
res += even->val > odd->val ? 1 : -1;
if(!odd->next) break;
even = odd->next;
odd = even->next;
}


return res == 0 ? "Tie" : res > 0 ? "Even" : "Odd";
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/03/01/PS/LeetCode/winner-of-the-linked-list-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.