From the course: C# Algorithms

Unlock the full course today

Join today to access over 24,600 courses taught by industry experts.

Stack algorithms: Implementing next greater element

Stack algorithms: Implementing next greater element - C# Tutorial

From the course: C# Algorithms

Stack algorithms: Implementing next greater element

- [Instructor] Let's translate the next greater element algorithm into C# code. The first step is to create the function. We have printNextGreaterElement that takes in an integer array arr. In order to print the next greater element for each item in the array, the array must have items. If it does not have items, then there's nothing to print out. We'll just write a new line and return. If the array has items, we need to find those next greater elements. We'll set up a stack to keep track of the elements we've already seen. Since it's an integer array, the stack will also hold int. We'll also push on that first element of the array. Then we'll iterate through the array to find that next greater element. In each iteration, we're checking whether or not a given item in the array is the next greatest element for the item on top of the stack. However, this only works if the stack has items. If the stack does not have items, then we simply push the next item onto the stack. If the stack…

Contents