Список на Java и проход по нему
есть программа, удаляющая из односвязного списка элементы c индексами от X до Y, в которой нет необходимости удалять каждый элемент в отдельности, а можно это сделать за один проход по связному списку. Как это можно сделать, исправив функцию myRemove?
public class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
this.next = null;
}
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
public Node() {
this.value = 0;
this.next = null;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public class MyList {
private Node head;
public MyList() {
this.head = null;
}
public void myRemove(int startIndex, int endIndex){
startIndex--;
for(int i = startIndex; i < endIndex; i++){
this.remove(startIndex);
}
}
public int size(){
int count = 0;
Node node = head;
while(node != null){
node = node.getNext();
count++;
}
return count;
}
public void add(int value){
Node node = head;
if(node == null){
head = new Node(value);
return;
}
while(node.getNext() != null){
node = node.getNext();
}
node.setNext(new Node(value));
}
public int get(int index){
int i = 0;
Node node = head;
while(node.getNext() != null && i < index){
node = node.getNext();
i++;
}
return node.getValue();
}
public void remove(int index){
if(index == 0 && head != null){
head = head.getNext();
return;
}
int i = 0;
Node node = head;
while(node.getNext() != null && i+1 < index){
node = node.getNext();
i++;
}
try{
node.setNext(node.getNext().getNext());
}catch(Exception ex){
node.setNext(null);
}
}
}
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.event.ActionEvent;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.util.Scanner;
public class Controller {
@FXML
private TextField saveField;
@FXML
private TextField secondField;
@FXML
private TextField loadFiled;
@FXML
private TextField firstField;
@FXML
private Stage stage;
@FXML
void load(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(stage);
String str = "";
try{
Scanner sc = new Scanner(file);
while(sc.hasNext()){
str+=sc.nextLine() + " ";
}
}catch(Exception ex){
ex.printStackTrace();
}
loadFiled.setText(str);
}
@FXML
void del(ActionEvent event) {
int firstIndex = Integer.parseInt(firstField.getText());
int secondIndex = Integer.parseInt(secondField.getText());
String[] arr = loadFiled.getText().split(" ");
MyList list = new MyList();
for(int i = 0; i < arr.length; i++){
list.add(Integer.parseInt(arr[i]));
}
list.myRemove(firstIndex,secondIndex);
String out = "";
for(int i = 0; i < list.size(); i++){
out+=list.get(i) + " ";
}
saveField.setText(out);
}
}