1
1
package com .codedifferently .lesson12 ;
2
2
3
- import java .util .Queue ;
4
-
5
3
public class Lesson12 {
6
4
7
5
/**
8
6
* Provide the solution to LeetCode 3062 here:
9
7
* https://github.com/yang-su2000/Leetcode-algorithm-practice/tree/master/3062-winner-of-the-linked-list-game
10
8
*/
11
9
public String gameResult (ListNode head ) {
12
- //make a linked list
13
- Queue <Integer > queue = new LinkedList <Integer >();
14
-
15
10
//create two variables to count points for "Odd" and "Even"
16
- int Odd = 0 ;
17
- int Even = 0 ;
18
- // Loop through the linked list to get pairs (so two nodes at a time)
11
+ int oddPoints = 0 ;
12
+ int evenPoints = 0 ;
19
13
14
+ // Loop through the linked list to get pairs (so two nodes at a time)
15
+ ListNode current = head ;
20
16
// Check each pair of nodes (odd and even):
21
17
// compare their values
22
-
23
- // add a point to "Odd" if the odd-indexed node is higher
24
-
25
- //add a point to "Even" if the even-indexed node is higher
26
-
18
+ while (current != null && current .next != null ) {
19
+ // add a point to "Even" if the odd-indexed node is higher
20
+ if (current .val < current .next .val ){
21
+ evenPoints ++;
22
+ }
23
+ //add a point to "Odd" if the even-indexed node is higher
24
+ else if (current .val > current .next .val ){
25
+ oddPoints ++;
26
+ }
27
+
28
+ current = current .next .next ;
29
+ }
27
30
// Decide the winner
28
31
// compare the points and choose the winner or tie
29
- if (Odd > Even ) {
32
+ if (oddPoints > evenPoints ) {
30
33
return ("Team odd wins!" );
31
- } else if (Even > Odd ){
34
+ } else if (evenPoints > oddPoints ){
32
35
return ("Team Even wins" );
33
36
} else {
34
37
return ("It's a tie" );
@@ -40,5 +43,3 @@ public String gameResult(ListNode head) {
40
43
// Constraints:
41
44
// The number of nodes in the list is in the range [2, 100].
42
45
// The number of nodes in the list is even. 1 <= Node.val <= 100
43
- // The value of each odd-indexed node is odd.
44
- // The value of each even-indexed node is even.
0 commit comments