Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Question? How can I called this method in the main, and how can I print it? Code : import java.util.LinkedList; import java.util.Stack; public class MergeSort

Question? How can I called this method in the main, and how can I print it? Code : import java.util.LinkedList; import java.util.Stack; public class MergeSort {

class inode { public int item; public inode next;

public inode(int i, inode n){ item = i; next = n; } public inode(int i){ item = i; next = null; } }

public LinkedList mergeSortStacks(LinkedList list) { Stack> stack1 = new Stack>(); Stack> stack2 = new Stack>(); /******************* * push all elements on stack1 *******************/ for (int i = 0; i < list.size(); i++) { inode node = new inode(list.get(i).item, list.get(i).next); LinkedList ll = new LinkedList<>(); ll.add(node); stack1.push(ll); } /****************** * pop two elements from one stack * merge them and push onto another stack * repeat this until merged *****************/ while (stack1.size()>1) { while (stack1.size()>1) { LinkedList ll1 = stack1.pop(); LinkedList ll2 = stack1.pop(); LinkedList mergedll=merge(ll1, ll2); stack2.push(mergedll); } while (stack2.size()>1) { LinkedList ll1 = stack2.pop(); LinkedList ll2 = stack2.pop(); LinkedList mergedll=merge(ll1, ll2); stack1.push(mergedll); } } return stack1.isEmpty() ? stack2.pop() : stack1.pop();

} private LinkedList merge(LinkedList ll1, LinkedList ll2) { LinkedList mergedll = new LinkedList(); int i = 0 , j=0; /*********************** * merge the elements until one or both of the lists reach their end **********************/ while(ll1.get(i) !=null && ll2.get(j)!=null){ if(ll1.get(i).item < ll1.get(i).item){ mergedll.add(ll1.get(i)); i++; }else{ mergedll.add(ll2.get(i)); j++; } } /***************************** * if ll2 was finised before ll1 then * put all remaining elements of ll1 into mergelist *****************************/ while(ll1.get(i)!=null){ mergedll.add(ll1.get(i)); i++; } /***************************** * if ll1 was finised before ll2 then * put all remaining

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Data Analysis Using SQL And Excel

Authors: Gordon S Linoff

2nd Edition

111902143X, 9781119021438

More Books

Students also viewed these Databases questions