In: Computer Science
Given lists L1, L2 and L3, delete all the nodes having even number in info part from the list L1 and insert into list L2 and all the nodes having odd numbers into list L3.
Code needed in java.
* Please note that I have created a program to create the list
and a function to perform the above operation.
* As odd and even both values have to be deleted, list L1 will be
empty after the operation and l2 and l3 will have data of l1 as per
the condition.
CODE:
Kindly upvote if
this helped. Comment for more info/help.
public class StackList {
class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public Node h = null;
public Node t = null;
public void push(int data) {
Node newNode = new Node(data);
if(h == null) {
h = newNode;
t = newNode;
}
else {
t.next = newNode;
t = newNode;
}
}
public void display() {
Node current = h;
if(h == null) {
System.out.println("No data in list");
return;
}
System.out.println("Values in list are ");
while(current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void popEvenFromL1andPushInL2(StackList l1 , StackList l2 , StackList l3) {
Node current = l1.h;
if(l1.h == null) {
System.out.println("No data in list");
return;
}
while(current != null) {
if(current.data % 2 == 0) {
l2.push(current.data);
}else {
l3.push(current.data);
}
current = current.next;
}
l1.h = null;
}
public static void main(String[] args) {
StackList sL = new StackList();
sL.push(4);
sL.push(2);
sL.push(5);
sL.push(8);
StackList sL1 = new StackList();
sL1.push(1);
sL1.push(2);
sL1.push(2);
sL1.push(5);
StackList sL2 = new StackList();
sL2.push(7);
sL2.push(12);
sL2.push(90);
sL2.push(81);
popEvenFromL1andPushInL2(sL, sL1, sL2);
sL.display(); // L1 list after operation
sL1.display();// L2 after operation
sL2.display(); // L3 after operation
}
}
OUTPUT
Explanation :