package org.wesome.dsalgo;
import lombok.Data;
import java.util.Objects;
public class LinkedList {
static Node head;
static int size = 0;
static void printMiddleUsingSize() {
System.out.println("LinkedList.printMiddleUsingSize");
int midIndex = size / 2;
System.out.print("midIndex " + midIndex);
Node node = head;
while (midIndex != 0) {
node = node.next;
midIndex--;
}
System.out.println(" middle element is " + node.data);
// for even size, we need to print both n and n+1, but since list starts from 0, to properly calculate the n, we need to add 1 in size first
if (((size + 1) % 2 == 0)) {
System.out.println("middle element is " + node.next.data);
}
}
//this method print the list using loop
static void printIteratively() {
System.out.println("LinkedList.printIteratively");
if (Objects.isNull(head)) {
System.out.println("Linked List is null = " + head);
return;
}
Node tempNode = head;
System.out.println("Linked List Size is " + size);
while (Objects.nonNull(tempNode)) {
System.out.println("Node = " + tempNode.data);
tempNode = tempNode.next;
}
}
static void addInLast(int element) {
System.out.println("\nLinkedList.addInLast " + element);
Node newNode = new Node(element);
if (Objects.isNull(head)) {
head = newNode;
return;
}
Node tempNode = head;
while (Objects.nonNull(tempNode.next)) {
tempNode = tempNode.next;
}
tempNode.next = newNode;
size++;
}
}
@Data
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}