Learn-dsa..in 30 days!



























CC-8 : Delete middle node of stack.

Description:

Given a Stack, delete its middle element, while preserving the order of the rest of the elements.

Test cases and expected outputs:

Input Parameters Expected outputs
Stack nodes:
9 <- 14 <- 17 <- 34 <- 21 <- 28 <-
Delete Middle Term, Stack nodes:
9 <- 14 <- 34 <- 21 <- 28 <-
Stack nodes:
9 <- 14 <- 17 <- 34 <- 21 <- 28 <- 35 <-
Delete Middle Term, Stack nodes:
9 <- 14 <- 17 <- 21 <- 28 <- 35 <-

Pseudocode:

Find the position of the middle term:
If size of stack is odd, middle term is (stackSize+1)/2.
If size of stack is even, we will consider (stackSize /2) as the middle term.
Create a temporary stack for processing purposes.
For indices 0 to (middle term-2), remove the data from input stack and add to temporary stack.
For index (middle term-1) remove it from input stack.
For all data from temp stack, remove the data from temp stack and add to input stack.
The middle term is deleted and order of stack has been preserved.

Code:

public class StackDeleteMiddle {
	
private Deque< Integer > tempStack=null;	

public Deque< Integer > deleteMiddle(Deque< Integer > stack) throws Exception{
	int n;
	if (stack.size() % 2!=0) { 
		n=(stack.size()+1)/2;
	}else {
		n=(stack.size())/2;
	}
	tempStack=new LinkedList<Integer>();
		
	for (int idx=0;idx < n; idx++) {
		if (idx != n-1) {
			tempStack.offerFirst((int)stack.poll());
		}else {
			stack.poll();
		}
		
	}
	while (tempStack.size() !=0) {
		stack.offerFirst((int) tempStack.poll());
	}
	return stack;
}
}	

Click here to download and run code and test cases !