-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssstack. java
More file actions
97 lines (79 loc) · 2.41 KB
/
Copy pathAssstack. java
File metadata and controls
97 lines (79 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class Stack {
private int top;
private int maxSize;
private int[] arr;
Stack(int maxSize) {
this.top = -1;
this.maxSize = maxSize;
arr = new int[maxSize];
}
public boolean isFull() {
return top >= (maxSize - 1);
}
public boolean push(int data) {
if (isFull()) {
return false;
} else {
arr[++top] = data;
return true;
}
}
public int peek() {
if (isEmpty())
return Integer.MIN_VALUE;
else
return arr[top];
}
public void display() {
if (isEmpty())
System.out.println("Stack is empty!");
else {
System.out.println("Displaying stack elements:");
for (int index = top; index >= 0; index--) {
System.out.println(arr[index]);
}
}
}
public boolean isEmpty() {
return top < 0;
}
public int pop() {
if (isEmpty())
return Integer.MIN_VALUE;
else
return arr[top--];
}
public int getMaxSize() {
return maxSize;
}
}
public class StackAssignment{
public static void main(String args[]) {
Stack stack = new Stack(10);
stack.push(15);
stack.push(20);
stack.push(30);
stack.push(40);
calculateSum(stack);
System.out.println("Updated stack:");
stack.display();
}
public static void calculateSum(Stack stack) {
int maxSize = stack.getMaxSize(); // Access maxSize using getter method
Stack tempStack = new Stack(maxSize); // Temporary stack to reorganize elements
// Step 1: Calculate the sum of all elements in the original stack
int sum = 0;
while (!stack.isEmpty()) {
int element = stack.pop();
sum += element;
tempStack.push(element); // Push elements into tempStack
}
// Step 2: Push the sum to the bottom of the stack
stack.push(sum);
// Step 3: Restore original stack order with sum at the bottom
while (!tempStack.isEmpty()) {
int element = tempStack.pop();
stack.push(element); // Push elements back to original stack
}
}
}