Write a java program to find the middle element of a given linked list. The file
ID: 3907676 • Letter: W
Question
Write a java program to find the middle element of a given linked list. The file name should be MiddleElement.java. (Also, you may use the java.import.LinkedList; function). You need a scanner and the arrows are apart of the input. The input will only have a single digit in between arrows.
Example: Your program should give similar output for the linked lists below:
Input: 5->NULL
Output: The middle element is [5]
Input: 4->5->NULL
Output: The middle element is [5]
Input: 3->4->5->NULL
Output: The middle element is [4]
Input: 2->-3->4->5->NULL
Output: The middle element is [4]
Input: 1->2->-3->4->5->NULL
Output: The middle element is [3]
Explanation / Answer
import java.util.Scanner; public class MiddleElement { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input: "); String[] words = in.nextLine().split("->"); if(words.length % 2 == 0) { System.out.printf("The middle element is [%s] ", words[(words.length-1)/2]); } else { System.out.printf("The middle element is [%s] ", words[words.length/2]); } } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.