Я создаю связанный список из пользовательского ввода и смог сделать это несколькими способами, но динамически он добавляется в заголовок, который, в свою очередь, делает ввод в обратном порядке. Мне нужно сослаться на список на l oop, но, похоже, я обнаружил, что в моем main, где я создаю второй узел в качестве списка на l oop, у меня есть NullPointerException в secondHead.next.
Вот мой код:
import java.io.*;
import java.lang.*;
import java.util.*;
class Node {
int data;
Node next;
Node prev;
Node(int value) {
this.data = value;
}
}
class MiddleLinkedListElement {
static Node head;
static Node inputHeadNode;
static int findMiddleLinkedListElement(int len) {
//function I loop through and get the Error for inputHeadNode.next
}
public static void push(int x) {
Node tempNode = new Node(x);
tempNode.next = head;
head = tempNode;
}
public static void main(String[] args) {
try {
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter an array of numbers starting with the number of arrays, then enter then the length and enter then the array.");
int count = Integer.parseInt(buffer.readLine());
while(count>0) {
int length = Integer.parseInt(buffer.readLine());
String[] inputArray = buffer.readLine().split(" ");
int tempCount = 0;
System.out.print("The input list is: ");
while(true) {
if(tempCount<length) {
push(Integer.parseInt(inputArray[tempCount]));
System.out.print(" " + inputArray[tempCount]);
} else
break;
tempCount++;
}
System.out.print("\n");
while(root!=null) {
inputHeadNode = new Node(root.data);
inputHeadNode.next = null;
root = root.next;
inputHeadNode = inputHeadNode.next;
}
System.out.println("The element is: " + findMiddleLinkedListElement(length));
count--;
}
} catch(IOException ex) {
System.out.println(ex);
}
}
}
Я рассмотрел GeeksForGeeks, которая дает решение, но я не понимаю, что, когда я использую ввод от пользователя, мой второй список не будет делать то же самое?