Skip to content

Commit 4572aa4

Browse files
Implemented the gameResult and stack methods
1 parent ac458a6 commit 4572aa4

File tree

2 files changed

+44
-15
lines changed

2 files changed

+44
-15
lines changed
Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,29 @@
11
import { ListNode } from './list_node.js';
22

33
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-
*/
4+
85
public gameResult(head: ListNode | null): string {
9-
return '';
10-
}
6+
if (!head) return 'Tie';
7+
8+
const ls = [0, 0];
9+
10+
while (head.next) {
11+
if (head.val !== head.next.val && head.val % 2 === 0) {
12+
if (head.val > head.next.val) {
13+
ls[head.val % 2] += 1;
14+
} else {
15+
ls[head.next.val % 2] += 1;
16+
}
17+
}
18+
head = head.next;
19+
}
20+
21+
if (ls[0] === ls[1]) {
22+
return 'Tie';
23+
} else if (ls[0] > ls[1]) {
24+
return 'Even';
25+
} else {
26+
return 'Odd';
27+
}
28+
}
1129
}

lesson_12/structs_ts/src/stack.ts

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,36 @@
11
import { ListNode } from './list_node.js';
22

33
export class Stack {
4-
private top: ListNode | undefined;
4+
private top: ListNode | null;
55

66
constructor() {
7-
this.top = undefined;
7+
this.top = null;
88
}
99

1010
push(value: number): void {
11-
throw new Error('Not implemented');
11+
const newNode = new ListNode(value, this.top ?? undefined);
12+
this.top = newNode;
1213
}
1314

14-
pop(): number | undefined {
15-
throw new Error('Not implemented');
15+
pop(): number {
16+
if (this.isEmpty()) {
17+
throw new Error('Stack Underflow: Cannot pop from an empty stack');
18+
}
19+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
20+
const poppedValue = this.top!.val;
21+
this.top = this.top?.next ?? null;
22+
return poppedValue;
1623
}
1724

18-
peek(): number | null {
19-
throw new Error('Not implemented');
25+
peek(): number {
26+
if (this.isEmpty()) {
27+
throw new Error('Stack is empty: Cannot peek');
28+
}
29+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
30+
return this.top!.val;
2031
}
2132

2233
isEmpty(): boolean {
23-
throw new Error('Not implemented');
34+
return this.top === null;
2435
}
25-
}
36+
}

0 commit comments

Comments
 (0)