1
1
import { ListNode } from './list_node.js' ;
2
2
3
3
export class Lesson12 {
4
- public gameResult ( head : ListNode ) : string {
4
+ public gameResult ( head : ListNode | null ) : string {
5
5
let scoreEven = 0 ;
6
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 ) {
7
+ let current : ListNode | null = head ;
8
+ let index = 0 ;
9
+
10
+ while ( current !== null ) {
11
+ // Check if the index is even
12
+ if ( index % 2 === 0 ) {
13
+ // Only check nextNode if current is not the last node
14
+ const nextNode = current . next ;
15
+ if ( nextNode != undefined ) {
16
+ if ( current . val > nextNode . val ) {
19
17
scoreEven += 1 ;
20
- } else if ( evenNum < oddNum ) {
18
+ } else if ( current . val < nextNode . val ) {
21
19
scoreOdd += 1 ;
22
20
}
23
21
}
24
22
}
23
+
24
+ // Move to the next node
25
+ current = current . next ?? null ;
26
+ index ++ ; // Increment the index
25
27
}
26
28
27
29
if ( scoreEven > scoreOdd ) {
@@ -33,29 +35,31 @@ export class Lesson12 {
33
35
}
34
36
}
35
37
36
- getElementAt ( head : ListNode | undefined , position : number ) : ListNode | undefined {
37
- let current = head ;
38
- let index = 0 ;
38
+
39
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
- }
40
+ // getElementAt(head: ListNode | undefined, position: number): ListNode | undefined {
41
+ // let current = head;
42
+ // let index = 0;
47
43
48
- return undefined ; // Return null if the position is out of bounds
49
- }
44
+ // while (current !== undefined) {
45
+ // if (index === position) {
46
+ // return current; // Return the node at the specified position
47
+ // }
48
+ // current = current.next; // Move to the next node
49
+ // index++; // Increment the index
50
+ // }
50
51
51
- getLength ( head : ListNode | undefined ) : number {
52
- let length = 0 ;
53
- let current = head ;
52
+ // return undefined; // Return null if the position is out of bounds
53
+ // }
54
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 ;
60
- }
55
+ // getLength(head: ListNode | undefined): number {
56
+ // let length = 0;
57
+ // let current = head;
58
+
59
+ // while (current !== undefined) {
60
+ // length++; // Increment to keep count through each element
61
+ // current = current.next; // Move on to the next element
62
+ // }
63
+ // return length;
64
+ // }
61
65
}
0 commit comments