|
1 | 1 | import { ListNode } from './list_node.js';
|
2 | 2 |
|
3 | 3 | export class Lesson12 {
|
4 |
| - /** |
5 |
| - * Provide the solution to LeetCode 3062 here: |
6 |
| - * https://github.com/yang-su2000/Leetcode-algorithm-practice/tree/master/3062-winner-of-the-linked-list-game |
7 |
| - */ |
8 |
| - public gameResult(head: ListNode | null): string { |
9 |
| - return ''; |
| 4 | + public gameResult(head: ListNode): string { |
| 5 | + let scoreEven = 0; |
| 6 | + let scoreOdd = 0; |
| 7 | + let evenNum = 0; |
| 8 | + let oddNum = 0; |
| 9 | + const length = this.getLength(head); |
| 10 | + |
| 11 | + for (let i = 0; i < length; i++) { |
| 12 | + const resultNode = this.getElementAt(head, i); |
| 13 | + if (resultNode) { |
| 14 | + if (i % 2 === 0) { |
| 15 | + evenNum = resultNode.val; |
| 16 | + } else { |
| 17 | + oddNum = resultNode.val; |
| 18 | + if (evenNum > oddNum) { |
| 19 | + scoreEven += 1; |
| 20 | + } else if (evenNum < oddNum) { |
| 21 | + scoreOdd += 1; |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + if (scoreEven > scoreOdd) { |
| 28 | + return "Even"; |
| 29 | + } else if (scoreEven < scoreOdd) { |
| 30 | + return "Odd"; |
| 31 | + } else { |
| 32 | + return "Tie"; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + getElementAt(head: ListNode | undefined, position: number): ListNode | undefined { |
| 37 | + let current = head; |
| 38 | + let index = 0; |
| 39 | + |
| 40 | + while (current !== undefined) { |
| 41 | + if (index === position) { |
| 42 | + return current; // Return the node at the specified position |
| 43 | + } |
| 44 | + current = current.next; // Move to the next node |
| 45 | + index++; // Increment the index |
| 46 | + } |
| 47 | + |
| 48 | + return undefined; // Return null if the position is out of bounds |
| 49 | + } |
| 50 | + |
| 51 | + getLength(head: ListNode | undefined): number { |
| 52 | + let length = 0; |
| 53 | + let current = head; |
| 54 | + |
| 55 | + while (current !== undefined) { |
| 56 | + length++; // Increment to keep count through each element |
| 57 | + current = current.next; // Move on to the next element |
| 58 | + } |
| 59 | + return length; |
10 | 60 | }
|
11 | 61 | }
|
0 commit comments