SlideShare a Scribd company logo
I have a stack in Java populated with integers. I'm trying to compare the elements in the stack to
determine which is the largest. Basically, I enter the element at the top of the stack into e then
pop each element off the stack and check to see if it is greater than the value stored in e. How can
I check to see if the next element in the stack is greater than the element stored in e?
E e = stk1.peek();
while(!stk1.empty())
{
if(stk1.peek() > e)
{
e=stk1.peek();
}
Solution
Using recursive approach we can sort the stack and the top element of stack would be the largest
integer.
Algorithm:
Sorting stack elements:
Inserting elements in sorted order:
Illustration:
First pop all the elements from the stack and store poped element in variable 'temp'. After
poping all the elements function's stack frame will look like:
Now stack is empty and 'insert_in_sorted_order()' function is called and it inserts 30 (from
stack frame #5) at the bottom of the stack. Now stack looks like below:
Now next element i.e. -5 (from stack frame #4) is picked. Since -5 < 30, -5 is inserted at the
bottom of stack. Now stack becomes:
Next 18 (from stack frame #3) is picked. Since 18 < 30, 18 is inserted below 30. Now stack
becomes:
Next 14 (from stack frame #2) is picked. Since 14 < 30 and 14 < 18, it is inserted below 18. Now
stack becomes:
Now -3 (from stack frame #1) is picked, as -3 < 30 and -3 < 18 and -3 < 14, it is inserted below
14. Now stack becomes:
Implementation:
/**
* Stack is represented using linked list
*/
public class Stack extends NativeClass {
private final IntContainer data = new IntContainer(this, 1);
private final Container> next = new Container>(this, 1){};
public int getData() {
return data.get();
}
public int setData(int newData) {
return data.set(newData);
}
public Container getNext() {
return next.get();
}
public Container setNext(Container newNext) {
return next.set(newNext);
}
public static Container nnc(Container orig) {
return Container.nnc(new TypeInfo>(){}, orig);
}
/**
* Utility function to initialize stack
*/
public static void initStack(Container[] s) {
s[0] = null;
}
/**
* Utility function to chcek if stack is empty
*/
public static int isEmpty(Stack[] s) {
if(s == null) {
return 1;
}
return 0;
}
/**
* Utility function to push an item to stack
*/
public static void push(Container[] s, int x) {
Container p = new Container(true, 1){};
p.get().setData(x);
p.get().setNext(s[0]);
s[0] = p;
}
/**
* Utility function to remove an item from stack
*/
public static int pop(Container[] s) {
int x;
Container temp;
x = s[0].get().getData();
temp = s[0];
s[0] = s[0].get().getNext();
nnc(temp).setNativeControlled(false);
return x;
}
/**
* Function to find top item
*/
public static int top(Stack[] s) {
return s[0].getData();
}
}
// Recursive function to insert an item x in sorted way
public static void sortedInsert(Container> s, int x) {
// Base case: Either stack is empty or newly inserted
// item is greater than top (more than all existing)
if(isEmpty(s.get()) != 0 || x > top(s.get())) {
push(s, x);
return;
}
// If top is greater, remove the top item and recur
int temp = pop(s);
sortedInsert(s, x);
// Put back the top item removed earlier
push(s, temp);
}
/**
* Function to sort stack
*/
public static void sortStack(Container> s) {
// If stack is not empty
if(isEmpty(s.get()) == 0) {
// Remove the top item
int x = pop(s);
// Sort remaining stack
sortStack(s);
// Push the top item back in sorted stack
sortedInsert(s, x);
}
}
// Utility function to print contents of stack
public static printStack(Container s) {
while(s != null) {
System.out.print(s.get().getData() + " ");
s = s.get().getNext();
}
System.out.println();
}
/**
* Driver Program
*/
public static void main(String[] args) {
Container> top = new Container>(1){};
initStack(top);
push(top, 30);
push(top, -5);
push(top, 18);
push(top, 14);
push(top, -3);
System.out.println("Stack elements before sorting:");
printStack(top.get());
sortStack(top);
System.out.println(" ");
System.out.println("Stack elements after sorting:");
printStack(top.get());
}
}

More Related Content

DOCX
(674335607) cs2309 java-lab-manual
DOCX
Need help with writing the test cases for the following code in java-.docx
PDF
ReversePoem.java ---------------------------------- public cl.pdf
PDF
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
PDF
Implement the ADT stack by using an array stack to contain its entri.pdf
PDF
Please review my code (java)Someone helped me with it but i cannot.pdf
PDF
later we create a specialstack class ,which inherits from stack cl.pdf
PDF
A linked stack is implemented using a standard Node class as follows.pdf
(674335607) cs2309 java-lab-manual
Need help with writing the test cases for the following code in java-.docx
ReversePoem.java ---------------------------------- public cl.pdf
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
Implement the ADT stack by using an array stack to contain its entri.pdf
Please review my code (java)Someone helped me with it but i cannot.pdf
later we create a specialstack class ,which inherits from stack cl.pdf
A linked stack is implemented using a standard Node class as follows.pdf

Similar to I have a stack in Java populated with integers. Im trying to compa.pdf (20)

PPT
DOCX
@author Derek Harter @cwid 123 45 678 @class .docx
PPTX
WINSEM2024-25_STS4022_SS_VL2024250500364_2024-12-21_Reference-Material-I.pptx
PPTX
Stack.pptx
DOCX
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
PPTX
Data Structure.pptx
PPT
Lec 4 Stack of Data Structures & Algorithms
PPT
Stacks queues
PDF
I need help in writing the test cases of the below methods i.pdf
DOCX
Use the following data set that compares age to average years lef.docx
PDF
Everything needs to be according to the instructions- thank you! SUPPO.pdf
DOCX
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
PPTX
Java Tutorial Lab 8
PDF
Hi,I have added the methods and main class as per your requirement.pdf
PPT
03 stacks and_queues_using_arrays
PDF
JAVA A double-ended queue is a list that allows the addition and.pdf
PPTX
Presentation topic is stick data structure
PPTX
Stack and Queue
PPTX
Data Structures and Agorithm: DS 06 Stack.pptx
PPTX
STACKS AND QUEUES CONCEPTS
@author Derek Harter @cwid 123 45 678 @class .docx
WINSEM2024-25_STS4022_SS_VL2024250500364_2024-12-21_Reference-Material-I.pptx
Stack.pptx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
Data Structure.pptx
Lec 4 Stack of Data Structures & Algorithms
Stacks queues
I need help in writing the test cases of the below methods i.pdf
Use the following data set that compares age to average years lef.docx
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Tutorial Lab 8
Hi,I have added the methods and main class as per your requirement.pdf
03 stacks and_queues_using_arrays
JAVA A double-ended queue is a list that allows the addition and.pdf
Presentation topic is stick data structure
Stack and Queue
Data Structures and Agorithm: DS 06 Stack.pptx
STACKS AND QUEUES CONCEPTS
Ad

More from JUSTSTYLISH3B2MOHALI (20)

PDF
In a business projects What material is typically contained in a pro.pdf
PDF
Implement the following flowchart in java. Start Request integer k f.pdf
PDF
If no chiasma forms between homologous chromosomes, what happens Th.pdf
PDF
If two organims form a symbiotic realtionship where they share t.pdf
PDF
I would appreciate help with these 4 questions. Thank You.1) Expla.pdf
PDF
How do I know when to use the sin^2+cos^2=1 identity....12 angle id.pdf
PDF
Hint List of commands to read and use use of wild card characters .pdf
PDF
Explain in Detail DTE-DCE TransmissionSolutionFirstly the DTE-.pdf
PDF
Explain the data component of social media information systems (SMIS).pdf
PDF
Figure CWhich structure in the cell shown in Figure C above stores.pdf
PDF
Coral reefs. How sensitive to changes in water temperature are coral .pdf
PDF
•0.336 moles of a weak, monoproticacid added to a final volume of 2..pdf
PDF
You are to simulate a dispatcher using a priority queue system in C+.pdf
PDF
Write a program that accepts an arithmetic expression of unsigned in.pdf
PDF
Why was the knowledge of macromolecules “structure” very important i.pdf
PDF
Why did the sovereign debt problem of Greece a country that accounts.pdf
PDF
Which of the following could be the most likely cause of a superi.pdf
PDF
What is the theory of public debt managementSolution1. Sove.pdf
PDF
This is a three part question. For each part the answer requires ide.pdf
PDF
Complete a personal SWOT analysis evaluating your understanding and .pdf
In a business projects What material is typically contained in a pro.pdf
Implement the following flowchart in java. Start Request integer k f.pdf
If no chiasma forms between homologous chromosomes, what happens Th.pdf
If two organims form a symbiotic realtionship where they share t.pdf
I would appreciate help with these 4 questions. Thank You.1) Expla.pdf
How do I know when to use the sin^2+cos^2=1 identity....12 angle id.pdf
Hint List of commands to read and use use of wild card characters .pdf
Explain in Detail DTE-DCE TransmissionSolutionFirstly the DTE-.pdf
Explain the data component of social media information systems (SMIS).pdf
Figure CWhich structure in the cell shown in Figure C above stores.pdf
Coral reefs. How sensitive to changes in water temperature are coral .pdf
•0.336 moles of a weak, monoproticacid added to a final volume of 2..pdf
You are to simulate a dispatcher using a priority queue system in C+.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdf
Why was the knowledge of macromolecules “structure” very important i.pdf
Why did the sovereign debt problem of Greece a country that accounts.pdf
Which of the following could be the most likely cause of a superi.pdf
What is the theory of public debt managementSolution1. Sove.pdf
This is a three part question. For each part the answer requires ide.pdf
Complete a personal SWOT analysis evaluating your understanding and .pdf
Ad

Recently uploaded (20)

PPTX
master seminar digital applications in india
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
What if we spent less time fighting change, and more time building what’s rig...
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Cell Structure & Organelles in detailed.
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Computing-Curriculum for Schools in Ghana
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Yogi Goddess Pres Conference Studio Updates
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
master seminar digital applications in india
Weekly quiz Compilation Jan -July 25.pdf
Microbial disease of the cardiovascular and lymphatic systems
UNIT III MENTAL HEALTH NURSING ASSESSMENT
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Paper A Mock Exam 9_ Attempt review.pdf.
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
What if we spent less time fighting change, and more time building what’s rig...
History, Philosophy and sociology of education (1).pptx
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Cell Structure & Organelles in detailed.
Final Presentation General Medicine 03-08-2024.pptx
Computing-Curriculum for Schools in Ghana
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Yogi Goddess Pres Conference Studio Updates
Orientation - ARALprogram of Deped to the Parents.pptx

I have a stack in Java populated with integers. Im trying to compa.pdf

  • 1. I have a stack in Java populated with integers. I'm trying to compare the elements in the stack to determine which is the largest. Basically, I enter the element at the top of the stack into e then pop each element off the stack and check to see if it is greater than the value stored in e. How can I check to see if the next element in the stack is greater than the element stored in e? E e = stk1.peek(); while(!stk1.empty()) { if(stk1.peek() > e) { e=stk1.peek(); } Solution Using recursive approach we can sort the stack and the top element of stack would be the largest integer. Algorithm: Sorting stack elements: Inserting elements in sorted order: Illustration: First pop all the elements from the stack and store poped element in variable 'temp'. After poping all the elements function's stack frame will look like: Now stack is empty and 'insert_in_sorted_order()' function is called and it inserts 30 (from stack frame #5) at the bottom of the stack. Now stack looks like below: Now next element i.e. -5 (from stack frame #4) is picked. Since -5 < 30, -5 is inserted at the bottom of stack. Now stack becomes: Next 18 (from stack frame #3) is picked. Since 18 < 30, 18 is inserted below 30. Now stack becomes: Next 14 (from stack frame #2) is picked. Since 14 < 30 and 14 < 18, it is inserted below 18. Now stack becomes: Now -3 (from stack frame #1) is picked, as -3 < 30 and -3 < 18 and -3 < 14, it is inserted below 14. Now stack becomes: Implementation: /** * Stack is represented using linked list
  • 2. */ public class Stack extends NativeClass { private final IntContainer data = new IntContainer(this, 1); private final Container> next = new Container>(this, 1){}; public int getData() { return data.get(); } public int setData(int newData) { return data.set(newData); } public Container getNext() { return next.get(); } public Container setNext(Container newNext) { return next.set(newNext); } public static Container nnc(Container orig) { return Container.nnc(new TypeInfo>(){}, orig); } /** * Utility function to initialize stack */ public static void initStack(Container[] s) { s[0] = null; } /** * Utility function to chcek if stack is empty */ public static int isEmpty(Stack[] s) { if(s == null) { return 1; } return 0; } /** * Utility function to push an item to stack
  • 3. */ public static void push(Container[] s, int x) { Container p = new Container(true, 1){}; p.get().setData(x); p.get().setNext(s[0]); s[0] = p; } /** * Utility function to remove an item from stack */ public static int pop(Container[] s) { int x; Container temp; x = s[0].get().getData(); temp = s[0]; s[0] = s[0].get().getNext(); nnc(temp).setNativeControlled(false); return x; } /** * Function to find top item */ public static int top(Stack[] s) { return s[0].getData(); } } // Recursive function to insert an item x in sorted way public static void sortedInsert(Container> s, int x) { // Base case: Either stack is empty or newly inserted // item is greater than top (more than all existing) if(isEmpty(s.get()) != 0 || x > top(s.get())) { push(s, x); return; } // If top is greater, remove the top item and recur
  • 4. int temp = pop(s); sortedInsert(s, x); // Put back the top item removed earlier push(s, temp); } /** * Function to sort stack */ public static void sortStack(Container> s) { // If stack is not empty if(isEmpty(s.get()) == 0) { // Remove the top item int x = pop(s); // Sort remaining stack sortStack(s); // Push the top item back in sorted stack sortedInsert(s, x); } } // Utility function to print contents of stack public static printStack(Container s) { while(s != null) { System.out.print(s.get().getData() + " "); s = s.get().getNext(); } System.out.println(); } /** * Driver Program */ public static void main(String[] args) { Container> top = new Container>(1){}; initStack(top); push(top, 30); push(top, -5); push(top, 18);
  • 5. push(top, 14); push(top, -3); System.out.println("Stack elements before sorting:"); printStack(top.get()); sortStack(top); System.out.println(" "); System.out.println("Stack elements after sorting:"); printStack(top.get()); } }