In: Computer Science
Q1) In the implementation of Singly linked list we had an integer variable called size that keeps track of how many elements in the list. Also, we have a reference “tail” that points to the last node in the list. You are asked to re-implement the concept of singly linked list without using variable size, and without using reference “tail”.
a) What are the methods of the main operation of singly linked list that need to be changed? Rewrite them according to this change (only the methods that need to be changed).
b) Will that affect the performance of any one of the main operations( size, isEmpty, first, last, addFirst, addLast, removeFirst, removeLast)? Explain.
Please answer based in the following codes:
public class Node <E>{
private E data;
private Node<E> next;
public Node(E d, Node<E> n)
{ data=d;
next=n; }
public E getData() { return data; }
public Node<E> getNext(){ return next; }
public void setNext(Node<E> n) { next=n; } }
--------------------------------------------------------------------
public class SinglyLinkedList <E>{
private Node<E> head=null;
private Node<E> tail=null;
private int size=0;
public SinglyLinkedList() { }
public int size() { return size;}
public boolean isEmpty() {return size==0;}
public E first()
{
if (isEmpty()) return null;
return head.getData();
}
public E last() // last()
{
if (isEmpty()) return null;
return head.getData();
}
public void addFirst(E e) // addFirst()
{
head=new Node<>(e,head);
if(size==0)
tail=head;
size++;
}
public void addLast(E e) //addLast()
{
Node<E> newest=new Node<>(e,null);
if(isEmpty())
head=newest;
else
tail.setNext(newest);
tail=newest;
size++;
}
public E removeFirst() // removeFirst()
{
if(isEmpty()) return null;
E answer=head.getData();
head=head.getNext();
size--;
if (size==0)
tail=null;
return answer;
}
public E removeLast() // removeLast()
{
if(isEmpty()) return null;
E answer=tail.getData();
if (head==tail)
head=tail=null;
else
{ Node<E> tmp=head;
while (tmp.getNext()!=tail)
tmp=tmp.getNext();
tmp.setNext(null);
tail=tmp;
}
size--;
return answer;
}
}
note: plzzz don't give dislike.....plzzz comment if you have any problem i will try to solve your problem.....plzzz give thumbs up i am in need....