if we have following List classes: public class LinkedList<T> { class ListNode {
ID: 3719498 • Letter: I
Question
if we have following List classes:
public class LinkedList<T> {
class ListNode {
protected T value;
protected ListNode next;
public ListNode(T val, ListNode nxt) {
value = val;
next = nxt;
}
public ListNode(T val) {
this(val, null);
}
public ListNode() {
this(null, null);
}
}
Write a method in java for the LinkedList class called boolean removeLast(T val) which removes the last occurrence of val from the list. The method should return true if it is successful by using a doubly linked list.
Explanation / Answer
public boolean removeLast(T val)
{
// if the list is empty
if( this.head = null )
return false;
// point trav to the head of the list
ListNode<T> trav = this.head;
// move to the last node
while( trav.next != null )
trav = trav.next;
// iterate the list in reverse order
// loop until the list ends
while( trav != null )
{
// if the current node is the required node
if( trav.value == val )
break;
// move to previous node
trav = trav.prev;
}
// if val is not present in list
if( trav == null )
return false;
// if the node to be deleted is the head of the list
if( trav == this.head )
{
// make the second node the head node
this.head = this.head.next;
// if there is a second node
if( this.head != null )
this.head.prev = null;
}
else
{
trav.prev.next = trav.next;
trav.next.prev = trav.prev;
}
return true;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.