In: Computer Science
please answer as text
You are given a Node class and a List class:
public class Node {
int data;
Node next;
Node(int d, Node n){
data = d;
next = n;
}
}
public class List{
Node header;
}
Write a java method insertNodeBefore( ) which takes two integers: int ref which is the data of the node that we need to insert a new node before, and int d which is the data of the new node we want to insert, for the Linked list mylist.
This is the mthod
void insertNodeBefore(int ref,int d)
{
if(header==null)
{
header=new
Node(d,null);
return;
}
if(header.next==null &&
header.data==ref)
{
Node newNode=new
Node(d, header);
header=newNode;
return;
}
if(header.data==ref)
{
Node newNode=new
Node(d, header);
header=newNode;
return;
}
Node curr=header;
Node pre=curr;
Node newNode=new Node(d,
null);
while(curr!=null &&
curr.data!=ref)
{
pre=curr;
curr=curr.next;
}
if(curr!=null)
{
pre.next=newNode;
newNode.next=curr;
}
}
For testing purpose i have created the full prodgrem
Node class
public class Node {
int data;
Node next;
Node(int d, Node n){
data = d;
next = n;
}
}
List.class
public class List {
Node header;
public List()
{
header=null;
}
void insertNodeBefore(int ref,int d)
{
if(header==null)
{
header=new
Node(d,null);
return;
}
if(header.next==null &&
header.data==ref)
{
Node newNode=new
Node(d, header);
header=newNode;
return;
}
if(header.data==ref)
{
Node newNode=new
Node(d, header);
header=newNode;
return;
}
Node curr=header;
Node pre=curr;
Node newNode=new Node(d,
null);
while(curr!=null &&
curr.data!=ref)
{
pre=curr;
curr=curr.next;
}
if(curr!=null)
{
pre.next=newNode;
newNode.next=curr;
}
}
void printList()
{
Node temp=header;
while(temp!=null)
{
System.out.print(temp.data+" ");
temp=temp.next;
}
}
}
ListTest class with main method
public class ListTest {
public static void main(String[] args) {
List lst=new List();
lst.insertNodeBefore(0, 30);
lst.insertNodeBefore(30, 20);
lst.insertNodeBefore(20, 10);
lst.printList();
}
}
output
If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.