Skip to content

Commit 297634e

Browse files
committed
Process a linked list.
1 parent ac458a6 commit 297634e

File tree

2 files changed

+51
-10
lines changed

2 files changed

+51
-10
lines changed

lesson_12/structs_java/structs_app/src/main/java/com/codedifferently/lesson12/Lesson12.java

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,33 @@
22

33
public class Lesson12 {
44

5-
/**
6-
* Provide the solution to LeetCode 3062 here:
7-
* https://github.com/yang-su2000/Leetcode-algorithm-practice/tree/master/3062-winner-of-the-linked-list-game
8-
*/
95
public String gameResult(ListNode head) {
10-
return null;
6+
int evenNumbers = 0;
7+
int oddNumbers = 0;
8+
9+
ListNode current = head;
10+
11+
// While "current" does not strictly equal null & current.next does not strictly equal null, the
12+
// current value is evenVariable, & oddVariable is the next value.
13+
while (current != null && current.next != null) {
14+
int evenVariable = current.val;
15+
int oddVariable = current.next.val;
16+
17+
if (oddVariable > evenVariable) {
18+
oddNumbers++;
19+
} else if (evenVariable > oddVariable) {
20+
evenNumbers++;
21+
}
22+
23+
current = current.next.next;
24+
}
25+
26+
if (oddNumbers > evenNumbers) {
27+
return "Odd";
28+
} else if (evenNumbers > oddNumbers) {
29+
return "Even";
30+
} else {
31+
return "Tie";
32+
}
1133
}
1234
}
Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,45 @@
11
package com.codedifferently.lesson12;
22

3-
/** Implement the below Stack by providing code for the class methods. */
43
public class Stack {
54
private ListNode top;
65

6+
private static class ListNode {
7+
int value;
8+
ListNode next;
9+
10+
ListNode(int value) {
11+
this.value = value;
12+
this.next = null;
13+
}
14+
}
15+
716
public Stack() {
817
this.top = null;
918
}
1019

1120
public void push(int value) {
12-
// Your code here
21+
ListNode newNode = new ListNode(value);
22+
newNode.next = top;
23+
top = newNode; // This will update top to the new node.
1324
}
1425

1526
public int pop() {
16-
return 0;
27+
if (isEmpty()) {
28+
throw new IllegalStateException("Stack is empty");
29+
}
30+
int poppedValue = top.value;
31+
top = top.next;
32+
return poppedValue;
1733
}
1834

1935
public int peek() {
20-
return 0;
36+
if (isEmpty()) {
37+
throw new IllegalStateException("Stack is empty");
38+
}
39+
return top.value;
2140
}
2241

2342
public boolean isEmpty() {
24-
return true;
43+
return top == null;
2544
}
2645
}

0 commit comments

Comments
 (0)