0% found this document useful (0 votes)
35 views

All Codes Java

The document contains code for solving several problems involving linked lists: 1) Merging k sorted linked lists using a priority queue. 2) Merging two sorted linked lists iteratively. 3) Checking if a linked list is a palindrome by reversing the second half and comparing. 4) Reversing the first k elements of a linked list. 5) Reordering a linked list to alternate elements from the first and second halves. 6) Rotating a linked list to the right by k positions.

Uploaded by

jay patel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

All Codes Java

The document contains code for solving several problems involving linked lists: 1) Merging k sorted linked lists using a priority queue. 2) Merging two sorted linked lists iteratively. 3) Checking if a linked list is a palindrome by reversing the second half and comparing. 4) Reversing the first k elements of a linked list. 5) Reordering a linked list to alternate elements from the first and second halves. 6) Rotating a linked list to the right by k positions.

Uploaded by

jay patel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

1)MERGE k SORTED LISTS

import java.util.*;
class Node{
int d;
Node next;
public Node(int data){
d=data;
}
}
public class Main{
public static Node mergeklists(List<Node> lists){
if(lists==null || lists.isEmpty()){
return null;
}
PriorityQueue<Node> minHeap = new PriorityQueue<>((a,b)->a.d-b.d);
for(Node list : lists){
if(list!=null){
minHeap.offer(list);
}
}
Node dummy=new Node(0);
Node current=dummy;
while(!minHeap.isEmpty()){
Node minnode=minHeap.poll();
current.next=minnode;
current=current.next;
if(minnode.next!=null){
minHeap.offer(minnode.next);
}
}
return dummy.next;
}
private static void printLinkedList(Node head){
while(head!=null){
System.out.println(head.d+" ");
head=head.next;
}
System.out.println();
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int k=sc.nextInt();
List<Node> lists=new ArrayList<>();
for(int i=0;i<k;i++){
int size=sc.nextInt();
Node head=new Node(sc.nextInt());
Node current=head;
for(int j=1;j<size;j++){
current.next=new Node(sc.nextInt());
current=current.next;
}
lists.add(head);
}
Node mergedlist = mergeklists(lists);
printLinkedList(mergedlist);
sc.close();
}
}

2)MERGE 2 SORTED LINKED LISTS

import java.util.*;
class Node{
int data;
Node next;
Node(int d){
data=d;
next=null;
}
}
class LinkedList{
Node head;
void add(int data){
Node new_node=new Node(data);
if(head==null){
head=new_node;
return;
}
Node current=head;
while(current.next!=null){
current=current.next;
}
current.next=new_node;
}
}
class Solution{
static Node merge(Node head1,Node head2){
if(head1==null){
return head2;
}
if(head2==null){
return head1;
}
Node ans;
if(head1.data<head2.data){
ans=head1;
head1=head1.next;
}
else{
ans=head2;
head2=head2.next;
}
Node temp=ans;
while(head1!=null && head2!=null){
if(head1.data<head2.data){
temp.next=head1;
head1=head1.next;
}
else{
temp.next=head2;
head2=head2.next;
}
temp=temp.next;
}
if(head1!=null){
temp.next=head1;
}
if(head2!=null){
temp.next=head2;
}
return ans;
}
}
class Main
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
LinkedList l1=new LinkedList();
for(int i=0;i<n;i++){
l1.add(sc.nextInt());
}
int m=sc.nextInt();
LinkedList l2=new LinkedList();
for(int i=0;i<m;i++){
l2.add(sc.nextInt());
}
Solution we=new Solution();
Node head=we.merge(l1.head,l2.head);
while(head!=null){
System.out.print(head.data+" ");
head=head.next;
}
}
}

3)PALINDROME OF A LIST

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

/* Name of the class has to be "Main" only if the class is public. */


class Main
{
class Node{
int data;
Node next;

public Node(int data){


this.data = data;
this.next = null;
}
}

public int size;

public Node head = null;


public Node tail = null;

public void addNode(int data){


Node newNode = new Node(data);
if(head==null){
head=newNode;
tail=newNode;
}
else{
tail.next=newNode;
tail=newNode;
}

size++;
}

public Node reverseList(Node temp){


Node current = temp;
Node prevNode = null, nextNode=null;

while(current!=null){
nextNode = current.next;
current.next = prevNode;
prevNode = current;
current = nextNode;
}
return prevNode;
}

public void isPalindrome(){


Node current = head;
boolean flag = true;

int mid = (size%2==0)?(size/2):((size+1)/2);

for(int i=1; i<mid; i++){


current=current.next;
}

Node revHead = reverseList(current.next);

while(head!=null && revHead!=null){


if(head.data!=revHead.data){
flag=false;
break;
}
head = head.next;
revHead = revHead.next;
}

if(flag)
System.out.println("true");
else
System.out.println("false");
}

public static void main (String[] args) throws java.lang.Exception


{
// your code goes here
Main sList = new Main();

Scanner scn = new Scanner(System.in);

String input = scn.nextLine();

String[] numbersStr = input.split("\\s+");

for (String numStr : numbersStr) {


int num = Integer.parseInt(numStr);
sList.addNode(num);
}

sList.isPalindrome();
}
}

4)REVERSE K ELEMENTS

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

/* Name of the class has to be "Main" only if the class is public. */


class Node
{
Node next;
int data;
Node(int d)
{
data=d;
next=null;
}
}
class Main
{
Node head;
void add(int d)
{
Node n=new Node(d);
if(head==null)
{
head=n;
}
else
{
Node curr=head;
while(curr.next!=null)
{
curr=curr.next;
}
curr.next=n;
}
}
Node reversek(Node h, int k)
{
Node curr=h;
Node prev=null;
Node next=null;
int count=0;
while(count<k && curr!=null)
{
next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
count++;
}
if(next!=null)
{
h.next=reversek(next,k);
}
else if(count<k)
{
curr=prev;
prev=null;
while(curr!=null)
{
next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
}
return prev;
}
return prev;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
Main m=new Main();
String s=sc.nextLine();
String sarr[]=s.split("\\s+");
for(String ele:sarr)
{
m.add(Integer.parseInt(ele));
}
String st=sc.nextLine();
int k=Integer.parseInt(st);
Node newhead=m.reversek(m.head, k);
while(newhead!=null)
{
System.out.print(newhead.data+" ");
newhead=newhead.next;
}
}
}

5)REORDER LIST

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

/* Name of the class has to be "Main" only if the class is public. */


class Node
{
Node next;
int data;
Node(int d)
{
data=d;
}
}
class Main
{
static Node head=null;
void add(int d)
{
Node n=new Node(d);
if(head==null)
{
head=n;
}
else
{
Node curr=head;
while(curr.next!=null)
{
curr=curr.next;
}
curr.next=n;
}
}
static Node mid(Node h)
{
Node sp=h;
Node fp=h;
while(fp!=null && fp.next!=null)
{
sp=sp.next;
fp=fp.next.next;
}
return sp;
}
static Node reverse(Node h)
{
Node curr=h;
Node prev=null;
Node next=null;
while(curr!=null)
{
next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
}
return prev;
}
Node reorder(Node h)
{
Node m=mid(h);
Node k=reverse(m.next);
m.next=null;
Node c1=h;
Node c2=k;
Node f1=null,f2=null;
while(c1!=null && c2!=null)
{
f1=c1.next;
c1.next=c2;
f2=c2.next;
c2.next=f1;
c1=f1;
c2=f2;
}
return h;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
Main m=new Main();
String s=sc.nextLine();
String sarr[]=s.split("\\s+");
for(String ele:sarr)
{
m.add(Integer.parseInt(ele));
}
Node newhead=m.reorder(head);
while(newhead!=null)
{
System.out.print(newhead.data+" ");
newhead=newhead.next;
}
}
}
6)ROTATE LIST

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

/* Name of the class has to be "Main" only if the class is public. */


class Node
{
Node next;
int data;
Node(int d)
{
data=d;
next=null;
}
}
class Main
{
public static Node rotateright(Node head, int k)
{
if(head==null||head.next==null||k==0)
return head;
int length=1;
Node tail=head;
while(tail.next!=null)
{
tail=tail.next;
length++;
}
k=k%length;
if(k==0)
return head;
Node newtail=head;
for(int i=0; i<length-k-1; i++)
{
newtail=newtail.next;
}
Node newhead=newtail.next;
newtail.next=null;
tail.next=head;
return newhead;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
String input=sc.nextLine();
String sarr[]=input.split("\\s+");
Node dummy=new Node(0);
Node curr=dummy;
for(String e:sarr)
{
int num=Integer.parseInt(e);
curr.next=new Node(num);
curr=curr.next;
}
Node head=dummy.next;
int x=sc.nextInt();
int k=sc.nextInt();
Node newhead=rotateright(head,2);
while(newhead!=null)
{
System.out.print(newhead.data+" ");
newhead=newhead.next;
}
}
}

7)ODD EVEN LINKED LIST

import java.util.Scanner;
import java.util.*;
class ListNode {
int val;
ListNode next;

public ListNode(int val) {


this.val = val;
}
}

class Solution {
public ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode evenHead = null, evenTail = null;
ListNode oddHead = null, oddTail = null;

ListNode current = head;

while (current != null) {


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 = current.next;
}

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

if (oddTail != null) {
oddTail.next = null;
}

return evenHead;
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] input = scanner.nextLine().split(" ");
ListNode head = null;
ListNode current = null;

for (String s : input) {


int val = Integer.parseInt(s);
if (head == null) {
head = new ListNode(val);
current = head;
} else {
current.next = new ListNode(val);
current = current.next;
}
}

Solution solution = new Solution();


ListNode result = solution.oddEvenList(head);
printLinkedList(result);
scanner.close();
}

private static void printLinkedList(ListNode head) {


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

8)LONGEST VALID PARANTHESIS

import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
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(max);
}
}

9)INFIX TO POSTFIX

import java.util.*;
class Main
{
public static boolean isOperator(char ch){
return ch=='+' || ch=='-' || ch=='*' || ch=='/';
}
public static int getPrecedence(char operator){
switch (operator){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
private static String infixToPostfix(String infix){
StringBuilder postfix=new StringBuilder();
Stack<Character> operatorStack=new Stack<>();
for(char ch:infix.toCharArray()){
if(Character.isLetterOrDigit(ch)){
postfix.append(ch);
}
else if(ch=='('){
operatorStack.push(ch);
}
else if(ch==')'){
while(!operatorStack.isEmpty() && operatorStack.peek()!='('){
postfix.append(operatorStack.pop());
}
operatorStack.pop();
}
else if(isOperator(ch)){
while(!operatorStack.isEmpty() &&
getPrecedence(ch)<=getPrecedence(operatorStack.peek())){

postfix.append(operatorStack.pop());
}
operatorStack.push(ch);
}
}
while(!operatorStack.isEmpty()){
postfix.append(operatorStack.pop());
}
return postfix.toString();
}
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
String infix1=sc.nextLine();
String postfix1=infixToPostfix(infix1);
System.out.println(postfix1);
sc.close();
}
}

10)EVALUATE POSTFIX EXPRESSION

import java.util.*;
public class Main {
public static int evaluatePostfix(String[] expressionTokens) {
Stack<Integer> stack = new Stack<>();
for (String token : expressionTokens) {
if (token.matches("-?\\d+")) {
stack.push(Integer.parseInt(token));
} else {
int operand2 = stack.pop();
int operand1 = stack.pop();
switch (token) {
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);
String postfixExpression = scanner.nextLine();
String[] expressionTokens = postfixExpression.split("\\s+");
int result = evaluatePostfix(expressionTokens);
System.out.println(result);
}
}

11)BASIC CALCULATOR

import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Stack<Integer> operands = new Stack<>();
Stack<Character> operators = new Stack<>();
String input = scanner.nextLine();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isDigit(c)) {
int num = c - '0';
while (i + 1 < input.length() && Character.isDigit(input.charAt(i + 1))) {
num = num * 10 + (input.charAt(i + 1) - '0');
i++;
}
operands.push(num);
}
else if (c == '+' || c == '-' || c == '*' || c == '/') {
while (!operators.isEmpty() && precedence(c) <= precedence(operators.peek())) {
evaluate(operands, operators);
}
operators.push(c);
}
}
while (!operators.isEmpty()) {
evaluate(operands, operators);
}
System.out.println(operands.pop());
}
private static int precedence(char c) {
if (c == '+' || c == '-') {
return 1;
}
else if (c == '*' || c == '/') {
return 2;
}
else {
return 0;
}
}
private static void evaluate(Stack<Integer> operands, Stack<Character> operators) {
int b = operands.pop();
int a = operands.pop();
char op = operators.pop();
int result;
if (op == '+') {
result = a + b;
}
else if (op == '-') {
result = a - b;
}
else if (op == '*') {
result = a * b;
}
else {
result = a / b;
}
operands.push(result);
}
}

12)IMPLEMENT STACK USING QUEUES

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

/* Name of the class has to be "Main" only if the class is public. */


class Main
{
Queue<Integer> q1;
Queue<Integer> q2;

Main()
{
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}

void push(int x)
{
if(!q1.isEmpty())
q1.offer(x);
else
q2.offer(x);
}

int pop()
{
if(q1.isEmpty() && q2.isEmpty())
return -1;
if(!q1.isEmpty())
{
while(q1.size()>1)
q2.offer(q1.poll());
return q1.poll();
}
else
{
while(q2.size()>1)
q1.offer(q2.poll());
return q2.poll();
}
}

public static void main (String[] args) throws java.lang.Exception


{
// your code goes here
Scanner sc = new Scanner(System.in);
Main st = new Main();
int n = sc.nextInt();
for(int i=0; i<n; i++)
{
int dec = sc.nextInt();
if(dec==1)
st.push(sc.nextInt());
else if(dec==2)
System.out.println(st.pop()+" ");
}
}
}

13)IMPLEMENT QUEUE USING STACKS

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

/* Name of the class has to be "Main" only if the class is public. */


class Main
{
Stack<Integer> s1;
Stack<Integer> s2;
Main()
{
s1 = new Stack<>();
s2 = new Stack<>();
}

void enqueue(int e)
{
s1.push(e);
}

int dequeue()
{
if(s2.isEmpty())
while(!s1.isEmpty())
s2.push(s1.pop());
if(!s2.isEmpty())
return s2.pop();
else
return -1;
}

public static void main (String[] args) throws java.lang.Exception


{
// your code goes here
Scanner sc = new Scanner(System.in);
Main q = new Main();
int n = sc.nextInt();
for(int i=0; i<n; i++)
{
int dec = sc.nextInt();
if(dec==1)
q.enqueue(sc.nextInt());
else if(dec==2)
System.out.print(q.dequeue()+" ");
}
}
}

14)BINARY RIGHT SIDE VIEW

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode(int val) {
this.val = val;
}
}

class BinaryTreeRightSideView {
public static void rightSideView(TreeNode root) {
if (root == null) {
return;
}

Queue<TreeNode> queue = new LinkedList<>();


queue.offer(root);

while (!queue.isEmpty()) {
int levelSize = queue.size();

for (int i = 0; i < levelSize; i++) {


TreeNode current = queue.poll();

// Print the rightmost node at each level


if (i == levelSize - 1) {
System.out.print(current.val + " ");
}

if (current.left != null) {
queue.offer(current.left);
}

if (current.right != null) {
queue.offer(current.right);
}
}
}
}

public static TreeNode buildTree(String[] nodes, int index) {


TreeNode root = null;
if (index < nodes.length) {
if (!nodes[index].equals("N")) {
root = new TreeNode(Integer.parseInt(nodes[index]));
root.left = buildTree(nodes, 2 * index + 1);
root.right = buildTree(nodes, 2 * index + 2);
}
}
return root;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

//System.out.print("Enter the number of test cases: ");


int t = scanner.nextInt();
scanner.nextLine(); // Consume newline

for (int i = 0; i < t; i++) {


//System.out.print("Enter the tree nodes for test case " + (i + 1) + ": ");
String[] nodes = scanner.nextLine().split(" ");

TreeNode root = buildTree(nodes, 0);

//System.out.print("Right View of the Tree: ");


rightSideView(root);
System.out.println();
}
}
}

15)DIAMETER OF BINARY TREE

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

/* Name of the class has to be "Main" only if the class is public. */


class Node{
int data;
Node left;
Node right;
Node(int data){
this.data=data;
left=null;
right=null;
}
}
class A{
int ans=0;
}
class Solution{
static int height(Node root,A a){
if(root==null){
return 0;
}
int left =height(root.left,a);
int right=height(root.right,a);
a.ans=Math.max(a.ans,left+right+1);
return 1+Math.max(left,right);
}
public static int diameter(Node root){
if(root==null){
return 0;

}
A a=new A();
height(root,a);
return a.ans;
}
}
class Main
{
public static Node buidTree(String str){
if(str.length()==0 || str.charAt(0)=='N'){
return null;
}
String ip[] =str.split(" ");
Node root=new Node(Integer.parseInt(ip[0]));
Queue<Node> queue= new LinkedList<>();
queue.add(root);
int i=1;
while(queue.size()>0 && i<ip.length){
Node currNode=queue.peek();
queue.remove();
String currVal=ip[i];
if(!currVal.equals("N")){
currNode.left=new Node(Integer.parseInt(currVal));
queue.add(currNode.left);
}
i++;
if(i>ip.length)break;
currVal=ip[i];
if(!currVal.equals("N")){
currNode.right=new Node(Integer.parseInt(currVal));
queue.add(currNode.right);
}
i++;
}
return root;
}
public static void main (String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1=br.readLine();
Node root1=buidTree(s1);
Solution g=new Solution();
System.out.println(g.diameter(root1));
}
}

You might also like