Advertisements
Advertisements
Question
A linked list is formed from the objects of the class given below:
class Node
{
doubel sal;
Node next;
}
Write an Algorithm OR a Method to add a node at the end of the an existing linked list. The method declaration is as follows:
void addNote(Node ptr, double ss)
Answer in Brief
Solution
class Node{
double sal;
Node next;
public Node(int data) {
this.sal = data;
this.next = null;
}
}
public void addNode(Node ptr, double ss) {
//Checks if the list is empty
ptr=new Node(ss);
if(head = null) {
//If list is empty, both head and tail will point
to new node
head = ptr;
tail = ptr;
}
else {
//newNode will be added after tail such that
tail’s next will point to newNode
tail.next = ptr;
//newNode will become new tail of the list
tail = ptr;
}
}
shaalaa.com
Implementation of Algorithms to Solve Problems
Is there an error in this question or solution?