|
| 1 | +package com.codedifferently.lesson12; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +public class Lesson12 { |
| 7 | + |
| 8 | + /** |
| 9 | + * Provide the solution to LeetCode 3062 here: |
| 10 | + * https://github.com/yang-su2000/Leetcode-algorithm-practice/tree/master/3062-winner-of-the-linked-list-game |
| 11 | + */ |
| 12 | + class TeamNode { |
| 13 | + int data; |
| 14 | + TeamNode next; |
| 15 | + |
| 16 | + public TeamNode(int data) { |
| 17 | + this.data = data; |
| 18 | + this.next = null; |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + class LinkedList { |
| 23 | + TeamNode head; |
| 24 | + |
| 25 | + public void add(int data) { |
| 26 | + TeamNode newTeamNode = new TeamNode(data); |
| 27 | + if (head == null) { |
| 28 | + head = newTeamNode; |
| 29 | + } else { |
| 30 | + TeamNode temp = head; |
| 31 | + while (temp.next != null) { |
| 32 | + temp = temp.next; |
| 33 | + } |
| 34 | + temp.next = newTeamNode; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public String gameResult(TeamNode head) { |
| 39 | + List<String> result = new ArrayList<>(); |
| 40 | + int evenCounter = 0; |
| 41 | + int oddCounter = 0; |
| 42 | + TeamNode current = head; |
| 43 | + |
| 44 | + while (current != null && current.next != null) { |
| 45 | + int evenValue = current.data; |
| 46 | + int oddValue = current.next.data; |
| 47 | + |
| 48 | + if (evenValue > oddValue) { |
| 49 | + result.add("even"); |
| 50 | + evenCounter++; |
| 51 | + } else { |
| 52 | + result.add("odd"); |
| 53 | + oddCounter++; |
| 54 | + } |
| 55 | + |
| 56 | + current = current.next.next; |
| 57 | + } |
| 58 | + |
| 59 | + String winningTeam; |
| 60 | + if (evenCounter > oddCounter) { |
| 61 | + winningTeam = "even"; |
| 62 | + } else if (oddCounter > evenCounter) { |
| 63 | + winningTeam = "odd"; |
| 64 | + } else { |
| 65 | + winningTeam = "tie"; |
| 66 | + } |
| 67 | + |
| 68 | + System.out.println("Nodes with higher values in each pair: " + result); |
| 69 | + System.out.println("The team with the most high-values is: " + winningTeam); |
| 70 | + |
| 71 | + return winningTeam; |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +public class Main { |
| 77 | + public static void main(String[] args) { |
| 78 | + LinkedList list = new LinkedList(); |
| 79 | + |
| 80 | + // Adding some nodes to the linked list |
| 81 | + list.add(2); |
| 82 | + list.add(5); |
| 83 | + list.add(4); |
| 84 | + list.add(7); |
| 85 | + list.add(20); |
| 86 | + list.add(5); |
| 87 | + |
| 88 | + // Call the function to compare pairs and determine the group with the most high-value pairs |
| 89 | + String winningTeam = list.gameResult(list.head); |
| 90 | + |
| 91 | + // Output the dominant group |
| 92 | + System.out.println("Team with most high-value pairs: " + winningTeam); |
| 93 | + } |
| 94 | +} |
0 commit comments