I have a problem when compiling the program. The remove method works well for in
ID: 3840219 • Letter: I
Question
I have a problem when compiling the program. The remove method works well for index = 0 and 1 in the main method (index 0 represents the head node). However, when I change the index to 2(the last index in the list), it has a runtime error. Can everyone tell me why and fix it for me?
public class List
{
public class Node{
private Node link;
private Object object;
public Node(){
link = null;
object = null;
}
public Node(Object obj, Node newLink){
object = obj;
link = newLink;
}
}
private Node head = null;
public List(){
head = null;
}
public int size(){
int size=0;
Node position = head;
if (head ==null){
size = 0;
}
else{
while (position!=null){
position = position.link;
size++;
}
}
return size;
}
public void append(Object next){
if (head==null){
head = new Node(next,head);
}
else{
Node position = head;
while(position.link!=null){
position = position.link;
}
Node a = new Node(next, null);
position.link = a;
}
}
public Object remove(int index){
int count = 0;
Node position = head;
int length = size();
try{
if (head == null){
throw new LinkedListException("Cannot remove an object from an empty list.");
}
else if (index>length){
throw new LinkedListException("index cannot be greater than the size of the list.");
}
else if (index<0){
throw new LinkedListException("index cannot be negative.");
}
else {
if (index==0){
head = head.link;
}
else if (index>0){
while (count position = position.link;
}
position.link = position.link.link;
}
}
}
catch (LinkedListException e){
System.out.println(e.getMessage());
}
return position.link.object;
}
public String toString(){
String list = "";
Node position = head;
while (position !=null){
list = list+position.object+" ";
position = position.link;
}
return list;
}
public static void main(String[] args) {
List multiple = new List();
multiple.append(10);
multiple.append(20);
multiple.append(30);
System.out.println("Multiple:"+ multiple);
multiple.remove(2);
System.out.println("Multiple:"+ multiple);
}
}
Expected output:
10 20
Explanation / Answer
public Object remove(int index){
int count = 0;
Node position = head;
Node deleted=new Node();
int length = size();
try{
if (head == null){
throw new LinkedListException("Cannot remove an object from an empty list.");
}
else if (index>length){
throw new LinkedListException("index cannot be greater than the size of the list.");
}
else if (index<0){
throw new LinkedListException("index cannot be negative.");
}
else {
if (index==0){
head = head.link;
}
else if (index>0){
while (++count <index)
position = position.link;
}
deleted=position.link;
position.link = position.link.link;
}
}
}
catch (LinkedListException e){
System.out.println(e.getMessage());
}
return deleted.object;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.