0% found this document useful (0 votes)
271 views29 pages

Linked List Operations in Java

The document discusses several operations on linked lists in Java: 1) Creating a linked list and adding elements to the beginning, end, and middle. 2) Merging two individually sorted linked lists into a single sorted list. 3) Reversing a linked list. 4) Checking if a linked list is a palindrome by reversing the second half and comparing it to the first half. 5) Merging k sorted linked lists into a single linked list, though it notes this implementation may be incorrect in some cases.

Uploaded by

manugj12m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
271 views29 pages

Linked List Operations in Java

The document discusses several operations on linked lists in Java: 1) Creating a linked list and adding elements to the beginning, end, and middle. 2) Merging two individually sorted linked lists into a single sorted list. 3) Reversing a linked list. 4) Checking if a linked list is a palindrome by reversing the second half and comparing it to the first half. 5) Merging k sorted linked lists into a single linked list, though it notes this implementation may be incorrect in some cases.

Uploaded by

manugj12m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

//20/02/2024 TUESDAY 09:05:04

//Creation of Linked List & 3 LINKKED LIST OPERATION (at BEGINNING , at END and at
MIDDLE)

import java.util.*; // Library Header File for java

public class Main {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int ele; //DECLARES ELEMENT
LinkedList LL=new LinkedList(); //CREATING OBJECT FOR CLASS LINKED LIST
while((ele=sc.nextInt())!=-1){ //WHILE LOOP TO TKAE INPUT FOR 1 LINKED
LIST
LL.insertAtEnd(ele); //INSERTS ELEMENT TO THE
LINKED LIST @ END
}
LL.insertAtMid(1,20); //INSERTS LL @
POSIITION=1 & VALUE=20
LL.print();
//PRINT FUNCTION
}
static class LinkedList{
Node head=null;
Node tail=null;
void insertAtBeg(int data){
Node newNode=new Node(data); //OBJECT CREATION FOR 'NODE' CLASS
if(head==null){
head=newNode;
}
else{
newNode.next=head;
head=newNode;
}
}
void insertAtEnd(int data){
Node newNode=new Node(data);
if(head==null){
head=newNode;
tail=newNode;
}
else{
tail.next=newNode;
tail=newNode;
}
}
void insertAtMid(int pos ,int data){
Node newNode=new Node(data);
if(pos==0){
insertAtBeg(data);
return;
}
Node temp=head;
for(int i=0;i<pos-1;i++){
temp=temp.next;
}
newNode.next=temp.next;
temp.next=newNode;
}
void print(){
Node temp=head;
while(temp!=null){
System.out.print(temp.data+"->");
temp=temp.next;
}
}
}
static class Node{
int data;
Node next=null; // Data type is Node & next holds address (which is initially
null)
Node(int data){
this.data=data;
}
}
}

___________________________________________________________________________________
__________________________________________________________________________
//MERGE TWO INDIVIDUALLY SORTED LINKEDLIST to form a SINGLE SORTED LL

//Examples
/*
3
1 5 8
6
0 1 2 6 9 10

0->1->1->2->5->6->8->9->10->NULL
*/
import java.util.*;

class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
LinkedList LL1=new LinkedList();
LinkedList LL2=new LinkedList();
int s1=sc.nextInt();
for(int i=0;i<s1;i++){
LL1.insertAtEnd(sc.nextInt());
}
int s2=sc.nextInt();
for(int i=0;i<s1;i++){
LL2.insertAtEnd(sc.nextInt());
}
merger listm=new merger();
Node sortedListNode=listm.merge(LL1.head,LL2.head);
listm.printMerge(sortedListNode);
}
static class merger{
Node merge(Node h1,Node h2){
Node dummy=new Node(0);
Node tail=dummy;
while(h1!=null & h2!=null){
if(h1.data<=h2.data){
tail.next=h1;
h1=h1.next;
}
else
{
tail.next=h2;
h2=h2.next;
}
tail=tail.next;
}
while(h1!=null){
tail.next=h1;
h1=h1.next;
tail=tail.next;
}
while(h2!=null){
tail.next=h2;
h2=h2.next;
tail=tail.next;
}
return dummy.next;
}
void printMerge(Node head)
{
Node temp = head;
while (temp != null) {
System.out.print(temp.data + "->");
temp = temp.next;
}
System.out.print("NULL");
}
}
static class LinkedList{
Node head=null;
Node tail=null;
void insertAtBeg(int data){
Node newNode=new Node(data);
if(head==null){
head=newNode;
}
else{
newNode.next=head;
head=newNode;
}
}
void insertAtEnd(int data){
Node newNode=new Node(data);
if(head==null){
head=newNode;
tail=newNode;
}
else{
tail.next=newNode;
tail=newNode;
}
}
void insertAtMid(int pos ,int data){
Node newNode=new Node(data);
if(pos==0){
insertAtBeg(data);
return;
}
Node temp=head;
for(int i=0;i<pos-1;i++){
temp=temp.next;
}
newNode.next=temp.next;
temp.next=newNode;
}
void print(){
Node temp=head;
while(temp!=null){
System.out.print(temp.data+"->");
temp=temp.next;
}
}
}
static class Node{
int data;
Node next=null;
Node(int data){
this.data=data;
}
}
}
___________________________________________________________________________________
___________________________________________________________________________
// Linked List Reversal

import java.util.*;

class Main{

static class Node{


int data;
Node next=null;
Node(int data){
this.data=data;
}
}
static class LinkedList{
Node head=null;
Node tail=null;
void insertAtEnd(int data){
Node newNode=new Node(data);
if(head==null){
head=newNode;
tail=newNode;
}
else{
tail.next=newNode;
tail=newNode;
}
}
Node reverseLL(){
Node curr=head;
Node next=null,prev=null;
while(curr!=null){
next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
}
return prev;
}
void print(Node temp){
//Node temp=head;
while(temp!=null){
System.out.print(temp.data+"->");
temp=temp.next;
}
System.out.println("\n");
}
}

public static void main(String args[]){


Scanner sc=new Scanner(System.in);
int elem;
LinkedList lz=new LinkedList();
while((elem=sc.nextInt())!=-1){
lz.insertAtEnd(elem);
}
lz.print(lz.head);
Node rnode=lz.reverseLL();
lz.print(rnode);
}
}
___________________________________________________________________________________
_________________________________________________________________________________
//Check if Linked List is Palindrome

import java.util.*;

class Main{

static class Node{


int data;
Node next=null;
Node(int data){
this.data=data;
}
}
static class LinkedList{
Node head=null;
Node tail=null;
void insertAtEnd(int data){
Node newNode=new Node(data);
if(head==null){
head=newNode;
tail=newNode;
}
else{
tail.next=newNode;
tail=newNode;
}
}
Node reverseLL(Node curr){
//Node curr=head;
Node next=null,prev=null;
while(curr!=null){
next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
}
return prev;
}
boolean palindrome(){
if(head==null || head.next==null){
return true;}
Node slow=head;
Node fast=head;

while(fast!=null && fast.next!=null){


slow=slow.next;
fast=fast.next.next;
}
Node secondHalf=reverseLL(slow);
Node firstHalf=head;

while(secondHalf!=null){
if(firstHalf.data!=secondHalf.data){
return false;}
firstHalf=firstHalf.next;
secondHalf=secondHalf.next;
}
return true;
}
void print(Node temp){
//Node temp=head;
while(temp!=null){
System.out.print(temp.data+"->");
temp=temp.next;
}
System.out.println("\n");
}
}

public static void main(String args[]){


Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
LinkedList lz=new LinkedList();
for(int i=0;i<n;i++){
lz.insertAtEnd(sc.nextInt());
}
if(lz.palindrome()){
System.out.println("True");
}
else{
System.out.println("False");
}
}
}
___________________________________________________________________________________
________________________________________________________________
// Merging k Sorted LINKEDLISTS to a single Linked list
// Note: Incorrect at some Instances
import java.util.*;

public class Main {

static class ListNode {


int data;
ListNode next;

public ListNode(int data) {


this.data = data;
}
}

static ListNode merge(ListNode[] heads) {


ListNode resultHead = null;
ListNode current = null;

PriorityQueue<ListNode> pq = new PriorityQueue<>((o1, o2) -> o1.data -


o2.data);

// Insert all heads into the priority queue


for (int i = 0; i < heads.length; i++) {
if (heads[i] != null) {
pq.offer(heads[i]);
}
}

while (!pq.isEmpty()) {
// Extract the min from the priority queue
ListNode node = pq.poll();

// Add it to the result Head


if (resultHead == null) {
resultHead = node;
current = node;
} else {
current.next = node;
current = current.next;
}

// Add the next List Node to the priority queue


if (node.next != null) {
pq.add(node.next);
}
}
return resultHead;
}

static void print(ListNode node) {


ListNode current = node;
while (current != null) {
System.out.print(current.data+"->");
current = current.next;
}
System.out.println();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int K= sc.nextInt();

ListNode[] lists = new ListNode[K];


int N = sc.nextInt();
for (int i = 0; i < K; i++) {
ListNode head = null;
ListNode current = null;
for (int j = 0; j < N; j++) {
int elem = sc.nextInt();
if (head == null) {
head = new ListNode(elem);
current = head;
} else {
current.next = new ListNode(elem);
current = current.next;
}
}
lists[i] = head;
}

ListNode result = merge(lists);


System.out.println("Merged Linked List: ");
print(result);
}
}
___________________________________________________________________________________
______________________________________________________________________________
import java.util.*;

class ListNode {
int val;
ListNode next;

public ListNode(int val) {


this.val = val;
}
}

public class Main {


public static ListNode mergeKLists(List<ListNode> lists) {
if (lists == null || lists.isEmpty()) {
return null;
}
PriorityQueue<ListNode> minHeap = new PriorityQueue<>((a, b) -> a.val -
b.val);
for (ListNode list : lists) {
if (list != null) {
minHeap.offer(list);
}
}
ListNode dummy = new ListNode(0);
ListNode current = dummy;
while (!minHeap.isEmpty()) {
ListNode minNode = minHeap.poll();
current.next = minNode;
current = current.next;
if (minNode.next != null) {
minHeap.offer(minNode.next);
}
}
return dummy.next;
}

private static void printLinkedList(ListNode head) {


while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int k = scanner.nextInt();
List<ListNode> lists = new ArrayList<>();
for (int i = 0; i < k; i++) {
ListNode head = new ListNode(scanner.nextInt());
ListNode current = head;
int num;
while ((num = scanner.nextInt()) != -1) {
current.next = new ListNode(num);
current = current.next;
}
lists.add(head);
}
ListNode mergedList = mergeKLists(lists);
printLinkedList(mergedList);
scanner.close();
}
}

___________________________________________________________________________________
____________________________________________________
//21/02/2024 WEDNESDAY 08:15:47

//STACK Implementation using Arrays

import java.util.*;

class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
int top=-1;
for(int i=0;i<n;i++){
String ip=sc.next();
if(ip.equals("push")){
top++;
arr[top]=sc.nextInt();
}
else if(ip.equals("pop")){
if (top==-1)
System.out.println("Stack underflow");
else{
arr[top]=0;
top--;
}
}
else if(ip.equals("print")){
for(int j=0;j<=top;j++){
System.out.println(arr[j]);
}
}
}
}
}
___________________________________________________________________________________
_________________________________________________________________________________
// STACK IMPLEMENTATION USING LINKED LIST AND IT'S ALLIED COMMANDS (Using Built-in
Header Function LIST)

import java.util.*;

class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
List<Integer> list=new LinkedList<>();
int top=-1;
for(;;){
String ip=sc.next();
if (ip.equals("stop")){
break;
}
if(ip.equals("push")){
list.add(sc.nextInt());
}
else if(ip.equals("pop")){
if (list.isEmpty())
System.out.println("\t\t -1"); //Stack Underflow
else{
int rem=list.remove(list.size()-1);
System.out.println("Popped Element: "+rem);
}
}
else if(ip.equals("print")){
if (list.isEmpty())
System.out.println("\t\t NULL"); //List Empty
else{
for(int j=0;j<list.size();j++){
System.out.println(list.get(j));
}
} }
else if(ip.equals("peak")){
System.out.println("Peak Element: "+list.get(list.size()-1));
}
}
}
}
___________________________________________________________________________________
_________________________________________________________________________________
//STACK IMPLEMENTATION USING LINKED LIST W/O 'Collections.io'

/* INPUT
push 1
push 2
push 3
pop
print
stop

OUTPUT
popped element 3
elements in stack
1
2
*/

import java.util.*;

public class Main


{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
LinkedList list=new LinkedList();
while(true){
String ip=sc.next();
if(ip.equals("push"))
{
list.push(sc.nextInt());
}
else if(ip.equals("pop"))
{

int rem=list.remove();
System.out.println("popped element "+rem);

}
else if(ip.equals("print"))
{
System.out.println("elements in stack");
list.print();

}
else if(ip.equals("stop"))
{
break;
}

}
}
static class LinkedList
{
Node head=null;
Node tail=null;
void push(int data)
{
Node newNode=new Node(data);
if(head==null)
{
head=newNode;
tail=newNode;
}
else
{
tail.next=newNode;
tail=newNode;
}
}
int remove()
{
Node temp=head;
while(temp.next.next!=null)
temp=temp.next;
int remEle=tail.data;
temp.next=null;
tail=temp;
return remEle;
}
void print()
{
Node temp=head;
while(temp!=null)
{
System.out.println(temp.data+" ");
temp=temp.next;
}
}
}
static class Node{
int data;
Node next=null;
Node(int data)
{
this.data=data;
}
}
}
___________________________________________________________________________________
__________________________________________________________________________________
//VALID Paranthesis using Stack

import java.util.Stack;
import java.util.*;
class Main
{
public static void main (String[]args)
{
Scanner sc=new Scanner(System.in);
String s = sc.next();
Stack < Integer > st = new Stack <> ();
int max = 0;
st.push (-1);
for (int i = 0; i < s.length (); i++)
{
char c = s.charAt (i);
if (c == '(')
{
st.push (i);
}
else
{
st.pop ();
if (st.isEmpty ())
{
st.push (i);
}
else
{
int len = i - st.peek ();
max = Math.max (max, len);
}
}
}
System.out.println ("Length of the longest valid parentheses substring: " +
max);
}
}
___________________________________________________________________________________
________________________________________________________________________________
//ODD & Even LinkedList (Ethnus)

import java.util.*;

class ListNode {
int val;
ListNode next;

ListNode(int val) {
this.val = val;
this.next = null;
}
}
class OddEvenLinkedList {
public ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null) {
return head;
}

// Separate even and odd nodes


ListNode evenHead = null;
ListNode evenTail = null;
ListNode oddHead = null;
ListNode oddTail = null;

ListNode current = head;


while (current != null) {
ListNode next = current.next;
if (current.val % 2 == 0) {
if (evenHead == null) {
evenHead = current;
evenTail = current;
} else {
evenTail.next = current;
evenTail = evenTail.next;
}
} else {
if (oddHead == null) {
oddHead = current;
oddTail = current;
} else {
oddTail.next = current;
oddTail = oddTail.next;
}
}
current.next = null; // Disconnect current node from the original list
current = next;
}

// Merge even and odd lists


if (evenHead == null) {
return oddHead;
} else {
evenTail.next = oddHead;
return evenHead;
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input for the linked list


String[] input = scanner.nextLine().split(" ");
ListNode head = null;
ListNode current = null;
for (String num : input) {
int val = Integer.parseInt(num);
ListNode newNode = new ListNode(val);
if (head == null) {
head = newNode;
current = newNode;
} else {
current.next = newNode;
current = current.next;
}
}

// Segregate even and odd numbers


OddEvenLinkedList segregator = new OddEvenLinkedList();
head = segregator.oddEvenList(head);

// Print the segregated linked list


while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
}
___________________________________________________________________________________
_________________________________________________________________________________
//INFIX to POSTFIX

import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String s=sc.next();
infixToPostfix(s);
}
static int prec(char c)
{
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
static char associativity(char c)
{
if (c == '^')
return 'R';
return 'L';
}
static void infixToPostfix(String s)
{
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <=
'9'))
{
result.append(c);
}
else if (c == '(')
{
stack.push(c);
}
else if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
{
result.append(stack.pop());
}
stack.pop();
}
else
{
while (!stack.isEmpty() && (prec(s.charAt(i)) < prec(stack.peek()) ||
prec(s.charAt(i)) == prec(stack.peek()) && associativity(s.charAt(i)) == 'L'))
{
result.append(stack.pop());
}
stack.push(c);
}
}
while (!stack.isEmpty())
{
result.append(stack.pop());
}
System.out.println(result);
}
}
___________________________________________________________________________________
_________________________________________________________________________________
INFIX to POSTFIX (method 2)

import java.util.Scanner;
import java.util.Stack;

public class Main {


static int precedence(char a) {
if (a == '+' || a == '-') {
return 1;
} else if (a == '*' || a == '/') {
return 2;
} else if (a == '^') {
return 3;
} else {
return 0;
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
Stack<Character> stack = new Stack<>();
String input = sc.nextLine(); // Using nextLine to read the entire line
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isLetterOrDigit(c)) {
result.append(c);
} else if (c == '(') {
stack.push(c);
} else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
result.append(stack.pop());
}
if (!stack.isEmpty() && stack.peek() == '(') {
stack.pop(); // Pop the '(' from the stack
}
} else { // Operator
while (!stack.isEmpty() && precedence(c) <=
precedence(stack.peek())) {
result.append(stack.pop());
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
result.append(stack.pop());
}
System.out.println(result.toString());
}
}
___________________________________________________________________________________
________________________________________________________________________
//22/02/2024 THURSDAY 08:25:47
//INORDER Traversal OF A Binary TREE
//input 8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1
//output 1 3 4 6 7 8 10 13 14
import java.util.*;

public class Main{


public static void main(String args[]){
Scanner sc=new Scanner(System.in);
//8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1
String str=sc.nextLine(); //Take i/p from user until next nextline
String[] strip=str.split(" ");
Queue <Node> queue=new LinkedList<> (); //Creating a Queue with inputs as
nodes via Linked List
Node root=new Node(Integer.parseInt(strip[0])); //Root Node = Initial Node
queue.add(root); //Root is added into the queue
for (int i=1;i<strip.length;i+=2){ //i=1 because root node (i=0) already
added & i+=2 because we are taking left and right node together in a loop
Node curr=queue.poll();
if(!strip[i].equals("-1")){
curr.left=new Node(Integer.parseInt(strip[i]));
queue.add(curr.left);
}
if(!strip[i+1].equals("-1")){
curr.right=new Node(Integer.parseInt(strip[i+1]));
queue.add(curr.right);
}
}
//System.out.println(queue);
inorder(root);
}
static void inorder (Node root){
if(root==null)
return;
inorder(root.left);
System.out.print(root.data+" ");
inorder(root.right);
}
static class Node{
int data;
Node left=null;
Node right=null;
Node(int data){
this.data=data;
}
}
}
___________________________________________________________________________________
_______________________________________________________________________________
//BINARY RIGHT SIDE VIEW
//input 8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1
//output [8, 10, 14, 13]

import java.util.*;

public class Main {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String[] strip = str.split(" ");
Queue<Node> queue = new LinkedList<>();
Node root = new Node(Integer.parseInt(strip[0]));
queue.add(root);
for (int i = 1; i < strip.length; i += 2) {
Node curr = queue.poll();
if (!strip[i].equals("-1")) {
curr.left = new Node(Integer.parseInt(strip[i]));
queue.add(curr.left);
}
if (!strip[i + 1].equals("-1")) {
curr.right = new Node(Integer.parseInt(strip[i + 1]));
queue.add(curr.right);
}
}
List<Integer> rightView = new ArrayList<>();
findRightView(root, 0, rightView);
for (int j=0;j<rightView.size();j++){
System.out.print(rightView.get(j)+" ");
}
}

static void findRightView(Node root, int depth, List<Integer> rightView) {


if (root == null)
return;
if (depth == rightView.size()) {
rightView.add(root.data);
findRightView(root.right, depth + 1, rightView);
findRightView(root.left, depth + 1, rightView);
}
}

static class Node {


int data;
Node left = null;
Node right = null;

Node(int data) {
this.data = data;
}
}
}

/*
-----------------------------------------------------------------------------------
--------------------------------
import java.util.*;

public class Main {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String strip[]=str.split(" ");
Queue<Node> queue = new LinkedList<>();
Node root = new Node(Integer.parseInt(strip[0]));
queue.add(root);
for (int i = 1; i < strip.length; i += 2) {
Node curr = queue.poll();
if (!strip[i].equals("N")) {
curr.left = new Node(Integer.parseInt(strip[i]));
queue.add(curr.left);
}
if (i+1<strip.length && !strip[i + 1].equals("N")) {
curr.right = new Node(Integer.parseInt(strip[i+1]));
queue.add(curr.right);
}
}
List<Integer> rightView = new ArrayList<>();
findRightView(root, 0, rightView);
for(int j=0;j<rightView.size();j++)
System.out.print(rightView.get(j)+" ");
}

static void findRightView(Node root, int depth, List<Integer> rightView) {


if (root == null)
return;
if (depth == rightView.size()) {
rightView.add(root.data);
findRightView(root.right, depth + 1, rightView);
findRightView(root.left, depth + 1, rightView);
}
}

static class Node {


int data;
Node left = null;
Node right = null;

Node(int data) {
this.data = data;
}
}
}
*/
___________________________________________________________________________________
__________________________________________________________________________________
//Print Node which do not have Siblings in Binary Tree
// Sibling Node

import java.util.*;

public class Main {


public static void main(String args[]) {
int count=0;
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String strip[]=str.split(" ");
Queue<Node> queue = new LinkedList<>();
Node root = new Node(Integer.parseInt(strip[0]));
queue.add(root);
for (int i = 1; i < strip.length; i += 2) {
Node curr = queue.poll();
if (!strip[i].equals("-1")) {
curr.left = new Node(Integer.parseInt(strip[i]));
queue.add(curr.left);
}
if (i+1<strip.length && !strip[i + 1].equals("-1")) {
curr.right = new Node(Integer.parseInt(strip[i+1]));
queue.add(curr.right);
}
}
List <Integer> single=new ArrayList<>();
noSibling(root,single);
System.out.println(single+" right siblings");
}
static void noSibling(Node root,List<Integer> single){
if (root==null){
return;
}
if (root.left!=null && root.right!=null){
noSibling(root.left,single);
noSibling(root.right,single);
}
else if(root.right!=null){
single.add(root.right.data);
noSibling(root.right,single);
}
else if(root.left!=null){
single.add(root.left.data);
noSibling(root.left,single);
}
}
static class Node {
int data;
Node left = null;
Node right = null;

Node(int data) {
this.data = data;
}
}
}

/* Google code
import java.util.*;
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class Main
{
Node root;
void printSingles(Node node)
{
if (node == null)
return;
if (node.left != null && node.right != null)
{
printSingles(node.left);
printSingles(node.right);
}

else if (node.right != null)


{
System.out.print(node.right.data + " ");
printSingles(node.right);
}
else if (node.left != null)
{
System.out.print( node.left.data + " ");
printSingles(node.left);
}
}
public static void main(String args[])
{
Main tree = new Main();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.right = new Node(4);
tree.root.right.left = new Node(-1);
tree.root.right.left.right = new Node(-1);
tree.root.right.left.left = new Node(7);
tree.printSingles(tree.root);
}
}
*/
___________________________________________________________________________________
_____________________________________________________________________________
//Evaluation of POSTFIX

import java.util.*;
public class Main
{
public static int evaluatePostfix (String expression)
{
Stack < Integer > stack = new Stack <> ();
for ( int i=0;i<expression.length();i++)
{
char c=expression.charAt(i);
if (Character.isDigit (c))
{
stack.push (Character.getNumericValue(c));
}
else
{
int operand2 = stack.pop ();
int operand1 = stack.pop ();
switch (c)
{
case '+':
stack.push (operand1 + operand2);
break;
case '-':
stack.push(operand1 - operand2);
break;
case '*':
stack.push(operand1 * operand2);
break;
case '/':
stack.push(operand1 / operand2);
break;
}
}
}
return stack.pop();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

int x=scanner.nextInt();

for (int i=0;i<x;i++)


{
String postfixExpression = scanner.next();
int result = evaluatePostfix(postfixExpression);
System.out.println(result);
}
}
}
/*
-----------------------------------------------------------------------------------
-----------------------------------
import java.util.*;

class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine(); // Read the postfix expression
int result = epx(str);
System.out.println("Result: " + result);
}

static int epx(String str) {


Stack<Integer> st = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isDigit(c)) {
st.push(c - '0'); // Push the actual integer value (not ASCII
value)
} else {
int se = st.pop(); // Second element
int fe = st.pop(); // First element
if (c == '+')
st.push(fe + se);
else if (c == '*')
st.push(fe * se);
else if (c == '-')
st.push(fe - se);
else if (c == '/')
st.push(fe / se);
}
}
return st.pop();
}
}
*/
___________________________________________________________________________________
____________________________________________________________________________
//23/02/2024 FRIDAY 08:25:47

//BACKTRACKING N-QUEENS
import java.util.*;
class Main {
static int sol[][];

public static boolean nqueen(int n, int col) {


if (col == n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (sol[i][j] == 1) {
System.out.print(j + 1 + " ");
}
}
}
System.out.println(); // Print a newline after printing a solution
return false;
}
for (int i = 0; i < n; i++) {
if (isSafe(i, col, n)) { // Index position; Column number; No. of
rows/Columns in matrix
sol[i][col] = 1;
if (nqueen(n, col + 1)) {
return true;
}
sol[i][col] = 0;
}
}
return false;
}

public static boolean isSafe(int row, int col, int n) {


// Horizontal dirn. line checking
for (int i = col; i >= 0; i--) {
if (sol[row][i] == 1) {
return false;
}
}
// Upper Diagonal Line Checking
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (sol[i][j] == 1) {
return false;
}
}
// Lower DiagonalCheck
for (int i = row, j = col; i < n && j >= 0; i++, j--) {
if (sol[i][j] == 1) {
return false;
}
}
return true;
}

public static void main(String args[]) {


Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // No. of Rows = No.of columns (CHESS BOARD)
if (n < 4) {
System.out.println("No possible ways to place " + n + " Queens in a " +
n + "x" + n + " matrix");
return;
}
sol = new int[n][n];
nqueen(n,0);
}
}
/*
-----------------------------------------------------------(Below Code Not
working)-----------------------------
//BACKTRACKING N-QUEENS ALGORITHM
import java.util.*;

class Main{
static int sol[][];

public static boolean nqueen(int n,int col){


if(col==n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(sol[j][i]==1){
System.out.print(j+1+" ");
}
}
}
return false;
}
for(int i=0;i<n;i++){
if(isSafe(i,col,n)){//Index position; Column number; No. of rows/Columns in
matrix
sol[i][col]=1;
if(nqueen(n,col+1)){
return true;
}
sol[i][col]=0;
}
}
return false;
}

public static boolean isSafe(int row, int col, int n){


for(int i=col;i<=0;i--){ //Horizontal dirn. line checking <--------- Q

if (sol[row][i]==1){
return false;
}
}
//Upper Diagonal Line Checking x
for(int i=row,j=col;i>=0 && j>=0;i--,j--){// \
if(sol[i][j]==1){// \
return false;// \
}// Q
}
//Lower DiagonalCheck
for(int i=row,j=col;i<n&&j>=0;i++,j--){
if(sol[i][j]==1){
return false;
}
}
return true;
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(); //No. of Rows = No.of columns (CHESS BOARD)
if (n<4){
System.out.println("No possible ways to place "+n+" Queens in a
"+n+"x"+n+" matrix");
return;
}
sol=new int[n][n];
nqueen(n,0); // 0 implies the the first column of the matrix
}
}
*/
___________________________________________________________________________________
_______________________________________________________________________
/* Output:

1*2*3*4*17*18*19*20
--5*6*7*14*15*16
----8*9*12*13
------10*11

*/
import java.util.*;

class Main{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int no=1;
int value=n*n+1;
for(int i=n;i>0;i--)
{
for(int h=0;h<n-i;h++)
System.out.print("--");
for (int j=0;j<i;j++)
System.out.print(no+++"*");
for(int k=0;k<i-1;k++)
System.out.print(value+++"*");
System.out.print(value);
value=value-2*(i-1);
System.out.println("");
}
}
}
___________________________________________________________________________________
_______
//SPIRAL PATTERN 1 2 3
//
4 5 6
// 7 8 9
//OUTPUT 1 2 3 6 9 8 7 4 5

import java.util.*;

class Main{
public static void main(String args[]){
int n=5,val=0,rem=0;
for(int i=n;i>0;i--){
for(int j=i;j>rem;j--){
val++;
System.out.print(val+" ");
}
for(int k=i;k>rem+1;k--){
val+=n;
System.out.print(val+" ");
}
for(int l=i;l>rem+1;l--){
val--;
System.out.print(val+" ");
}
for(int m=i-1;m>rem+1;m--){
val-=n;
System.out.print(val+" ");
}
rem++;
}
}
}
------------------------------------------------------------
import java.util.*;

class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[][] arr=new int[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
arr[i][j]=sc.nextInt();

int round=(int)Math.ceil(n/2.0);
for(int i=0;i<round;i++){
for(int j=i;j<=n-i-1;j++)
System.out.print(arr[i][j]+" ");

for(int j=i+1;j<=n-i-1;j++)
System.out.print(arr[j][n-i-1]+" ");

for(int j=n-i-2;j>=i;j--)
System.out.print(arr[n-i-1][j]+" ");

for(int j=n-i-2;j>i;j--)
System.out.print(arr[j][i]+" "); //arr[changing][constant]
}
}
}
__________________________________________________________________________________
//SUDOKU BACKTRACKING

import java.io.*;
import java.util.*;

public class Main {


static int[][] grid;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int row=sc.nextInt();
int col=sc.nextInt();
int[][] grid=new int[row][col];
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
grid[i][j]=sc.nextInt();

if(sudokoSolver(grid,0,0))
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
System.out.print(grid[i][j]+" ");
System.out.println();

}
}
else
System.out.println("No Solution exists");

static boolean sudokoSolver(int[][] grid,int row,int col)


{
if(row==grid.length)
return true;
int nrow=0;
int ncol=0;
if(col!=grid.length-1)
{
nrow=row;
ncol=col+1;
}
else
{
nrow=row+1;
ncol=0;
}

if(grid[row][col]!=0)
{
if(sudokoSolver(grid,nrow,ncol))
return true;

}
else
{
for(int i=1;i<=9;i++)
{
if(isSafe(grid,row,col,i))
{
grid[row][col]=i;
if(sudokoSolver(grid,nrow,ncol))
{
return true;
}
else
{
grid[row][col]=0;
}
}

}
}
return false;
}

static boolean isSafe(int[][] grid,int row,int col,int number)


{
for(int i=0;i<grid.length;i++)
{
if(grid[i][col]==number)
return false;
if(grid[row][i]==number)
return false;
}

// 3*3 box check


int sr=(row/3)*3;
int sc=(col/3)*3;
for(int i=sr;i<sr+3;i++)
for(int j=sc;j<sc+3;j++)
if(grid[i][j]==number)
return false;
return true;
}
}
/*

//input
9
9
3 0 6 5 0 8 4 0 0
5 2 0 0 0 0 0 0 0
0 8 7 0 0 0 0 3 1
0 0 3 0 1 0 0 8 0
9 0 0 8 6 3 0 0 5
0 5 0 0 9 0 6 0 0
1 3 0 0 0 0 2 5 0
0 0 0 0 0 0 0 7 4
0 0 5 2 0 6 3 0 0
output:
3 1 6 5 7 8 4 9 2
5 2 9 1 3 4 7 6 8
4 8 7 6 2 9 5 3 1
2 6 3 4 1 5 9 8 7
9 7 4 8 6 3 1 2 5
8 5 1 7 9 2 6 4 3
1 3 8 9 4 7 2 5 6
6 9 2 3 5 1 8 7 4
7 4 5 2 8 6 3 1 9
*/
_______________________________________________
//prefix suffix (Code is incorrect I think)
//koi bkl hi hoga jo cut krega

import java.io.*;
import java.util.*;

public class Main {

public static void main(String[] args) {


String str=sc.nextLine();
int[] lps=new int[str.length()];
String res=lhp(str,lps);
System.out.print(res);
}

static String lhp(String str,int[] lps)


{
int i=0;
int j=1;
while(j<str.length())
{
if(str.charAt(i)==str.charAt(j))
{
i++;
lps[j]=i;
j++;
}
else
{
if(i==0)
j++;
else
i=lps[i-1];
}
}
return str.substring(0,i);
}

______________________________________________________----
Trapped Rainwater 2d

You might also like