Skip to content

Commit 2b3e49d

Browse files
author
jjcapparell
committed
feat: edited methods for Lesson12.java and Stack.java
1 parent 439780a commit 2b3e49d

File tree

2 files changed

+70
-9
lines changed

2 files changed

+70
-9
lines changed

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

Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,63 @@
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 score_even = 0;
7+
int score_odd = 0;
8+
int evenNum = 0;
9+
int oddNum = 0;
10+
for (int i=0;i<getLength(head);i++){
11+
if (i%2==0){
12+
ListNode resultNode = getElementAt(head, i);
13+
evenNum = resultNode.val;
14+
}
15+
else if (i%2==1){
16+
ListNode resultNode = getElementAt(head, i);
17+
oddNum = resultNode.val;
18+
if(evenNum>oddNum){
19+
score_even+=1;
20+
}
21+
else if(evenNum<oddNum){
22+
score_odd+=1;
23+
}
24+
}
25+
}
26+
if (score_even>score_odd){
27+
return "Even";
28+
}
29+
else if (score_even<score_odd){
30+
return "Odd";
31+
}
32+
else {
33+
return "Tie";
34+
}
35+
}
36+
37+
public ListNode getElementAt(ListNode head, int position) {
38+
ListNode current = head;
39+
int index = 0;
40+
41+
// Traverse the list until reaching the desired position
42+
while (current != null) {
43+
if (index == position) {
44+
return current; // Return the node at the specified position
45+
}
46+
current = current.next; // Move to the next node
47+
index++; // Increment the index
48+
}
49+
50+
return null; // Return null if the position is out of bounds
51+
}
52+
53+
public int getLength(ListNode head) {
54+
int length = 0;
55+
ListNode current = head;
56+
57+
while (current != null) {
58+
length++; // increment to keep count through each element
59+
current = current.next; // moves on to next element
60+
}
61+
62+
return length;
1163
}
1264
}

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

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,27 @@ public Stack() {
99
}
1010

1111
public void push(int value) {
12-
// Your code here
12+
ListNode newNode = new ListNode(value, top);
13+
top = newNode;
1314
}
1415

1516
public int pop() {
16-
return 0;
17+
if (isEmpty()) {
18+
throw new IllegalStateException("Stack is empty");
19+
}
20+
int value = top.val;
21+
top =top.next;
22+
return value;
1723
}
1824

1925
public int peek() {
20-
return 0;
26+
if (isEmpty()) {
27+
throw new IllegalStateException("Stack is empty");
28+
}
29+
return top.val;
2130
}
2231

2332
public boolean isEmpty() {
24-
return true;
33+
return top == null;
2534
}
2635
}

0 commit comments

Comments
 (0)