In: Computer Science
public class StringNode { private String item; private StringNode next; } public class StringLL { private StringNode head; private int size; public StringLL(){ head = null; size = 0; } public void add(String s){ add(size,s); } public boolean add(int index, String s){ ... } public String remove(int index){ ... } }
In the above code add(int index, String s) creates a StringNode and adds it to the linked list at position index, and remove(int index) removes the StringNode at position index.
Which cases does add(index,s) need to consider? and
Complete the next code fragment in remove(int index) that locates the predecessor of the node to be removed.
// locate predecessor curr = head; for( ){ curr=curr.getNext(); }
Java code for above problem
public class StringNode
{
private String item;
private StringNode next;
public StringNode(String item)
{
this.item=item;
this.next=null;
}
public String getItem()
{
return this.item;
}
public void setItem(String data)
{
this.item=item;
}
public StringNode getNext()
{
return this.next;
}
public void setNext(StringNode next)
{
this.next=next;
}
}
public class StringLL
{
private StringNode head;
private int size;
public StringLL()
{
head =
null;
size =
0;
}
public void add(String s)
{
add(size,s);
}
public boolean add(int index, String s)
{
StringNode new_node=new
StringNode(s);
StringNode node=this.head;
StringNode prev=null;
while(node!=null &&
index>0)
{
prev=node;
node=node.getNext();
index--;
}
if(prev==null)
{
new_node.setNext(this.head);
this.head=new_node;
}
else
{
new_node.setNext(prev.getNext());
prev.setNext(new_node);
}
size++;
return true;
}
public String remove(int index)
{
StringNode node=this.head;
StringNode prev=null;
while(node!=null &&
index>0)
{
prev=node;
node=node.getNext();
index--;
}
if(node==null)
{
return "";
}
String result="";
if(prev==null)
{
result=this.head.getItem();
this.head=this.head.getNext();
}
else
{
result=node.getItem();
prev.setNext(node.getNext());
}
return result;
}
}
Mention in comments if any mistakes or errors are found, Thank you.