-1
I am wanting to remove the last element from a chained list by typing position n:
when I type 1,2,3,4,5 of and n=2, I want it to stay 1,2,3,5 but it’s giving 1,2,3.
import java.io.IOException;
import java.util.Scanner;
class No {
int val;
No prox;
No(int x) {
val = x;
}
}
public class Main {
public static No removeNElementoDoFim(No cabeca, int n) {
if (cabeca == null) {
return null;
} else {
No ultimoNo = cabeca.prox;
No penultimoNo = cabeca.prox;
for (int i = 0; ultimoNo.prox != null && i < n; i++) {
penultimoNo = ultimoNo;
ultimoNo = ultimoNo.prox;
}
penultimoNo.prox = null;
return cabeca;
}
}
public static int[] stringToIntegerArray(String input) {
input = input.trim();
if (input.length() == 0) {
return new int[0];
}
String[] parts = input.split(",");
int[] output = new int[parts.length];
for (int index = 0; index < parts.length; index++) {
if (parts[index].trim().length() > 0) {
String part = parts[index].trim();
output[index] = Integer.parseInt(part);
}
}
return output;
}
public static No stringToNo(String input) {
int[] nodeValues = stringToIntegerArray(input);
No root = new No(0);
No ptr = root;
for (int item : nodeValues) {
ptr.prox = new No(item);
ptr = ptr.prox;
}
return root.prox;
}
public static String noToString(No no) {
if (no == null) {
return "[]";
}
String result = "";
while (no != null) {
result += Integer.toString(no.val) + ", ";
no = no.prox;
}
return "[" + result.substring(0, result.length() - 2) + "]";
}
public static void main(String[] args) throws IOException {
Scanner scann = new Scanner(System.in);
String line;
while (scann.hasNextLine()) {
line = scann.nextLine();
No cabeca = stringToNo(line);
int n = Integer.valueOf(scann.nextLine());
No ret = removeNElementoDoFim(cabeca, n);
String out = noToString(ret);
System.out.print(out);
}
scann.close();
}
}