Skip to content

Commit a778ef3

Browse files
committed
Array based stack fixes
1 parent ca09567 commit a778ef3

File tree

2 files changed

+7
-9
lines changed

2 files changed

+7
-9
lines changed

src/com/deepak/data/structures/Stack/ArrayBasedStack.java

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,8 @@ public Object pop() {
5353
if (size == 0) {
5454
throw new NoSuchElementException("Cannot delete from a empty Stack");
5555
}
56-
Object result = array[0];
57-
for (int i = 0; i < array.length - 1; i++) {
58-
array[i] = array[i + 1];
59-
}
56+
Object result = array[size - 1];
57+
array[size - 1] = null;
6058
size--;
6159
return result;
6260
}
@@ -70,7 +68,7 @@ public Object peek() {
7068
if (size == 0) {
7169
throw new NoSuchElementException("Cannot peek from a empty Stack");
7270
}
73-
return array[0];
71+
return array[size - 1];
7472
}
7573

7674
/**

test/com/deepak/data/structures/Stack/ArrayBasedStackTest.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,9 @@ public void testPop() {
4343
stack.push(35);
4444
stack.push(13);
4545
Assert.assertTrue(stack.size() == 4);
46-
Assert.assertEquals(stack.pop(), 3);
47-
Assert.assertEquals(stack.pop(), 17);
46+
Assert.assertEquals(stack.pop(), 13);
4847
Assert.assertEquals(stack.pop(), 35);
48+
Assert.assertEquals(stack.pop(), 17);
4949
Assert.assertTrue(stack.size() == 1);
5050
}
5151

@@ -62,11 +62,11 @@ public void testPeek() {
6262
stack.push(35);
6363
stack.push(13);
6464
Assert.assertTrue(stack.size() == 4);
65-
Assert.assertEquals(stack.peek(), 3);
65+
Assert.assertEquals(stack.peek(), 13);
6666
Assert.assertTrue(stack.size() == 4);
6767
stack.pop();
6868
Assert.assertTrue(stack.size() == 3);
69-
Assert.assertEquals(stack.peek(), 17);
69+
Assert.assertEquals(stack.peek(), 35);
7070
}
7171

7272
}

0 commit comments

Comments
 (0)