package org.wesome.dsalgo;
import lombok.Data;
import java.util.Objects;
public class LinkedList {
static Node head, merged;
static void print(Node head) {
if (Objects.isNull(head)) {
System.out.println("list is null = " + head);
return;
}
Node tempNode = head;
while (Objects.nonNull(tempNode)) {
System.out.println("Node = " + tempNode.data);
tempNode = tempNode.next;
}
}
static Node addInLast(Node head, int element) {
Node newNode = new Node(element);
if (Objects.isNull(head)) {
head = newNode;
return head;
}
Node tempNode = head;
while (Objects.nonNull(tempNode.next)) {
tempNode = tempNode.next;
}
tempNode.next = newNode;
return head;
}
public static Node mergeTwoSortedLinkedList(Node list1, Node list2) {
System.out.println("LinkedList.mergeTwoSortedLinkedList");
if (Objects.isNull(list1)) {
System.out.println("list1 is null = " + head);
return list2;
}
if (Objects.isNull(list2)) {
System.out.println("list2 is null = " + head);
return list1;
}
while (Objects.nonNull(list1) && Objects.nonNull(list2)) {
if (list1.data <= list2.data) {
merged = addInLast(merged, list1.data);
list1 = list1.next;
} else {
merged = addInLast(merged, list2.data);
list2 = list2.next;
}
}
return merged;
}
@Data
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Test;
import org.wesome.dsalgo.LinkedList.Node;
import static org.wesome.dsalgo.LinkedList.print;
public class LinkedListTest {
@Test
void removeDuplicates() {
Node list1 = null;
for (int i = 0; i <= 10; i++) {
if ((i % 2 == 0)) {
list1 = LinkedList.addInLast(list1, i);
}
}
print(list1);
Node list2 = null;
for (int i = 0; i <= 10; i++) {
if ((i % 2 != 0)) {
list2 = LinkedList.addInLast(list2, i);
}
}
print(list2);
Node merged = LinkedList.mergeTwoSortedLinkedList(list1, list2);
print(merged);
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.2.0"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}