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 - 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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
-
What is a queue?2m
-
(Locked)
Standard queue operations in C#4m 24s
-
(Locked)
Queue algorithms: Generate binary numbers5m 21s
-
(Locked)
What is a stack?1m 56s
-
(Locked)
Basic stack operations in C#4m 23s
-
(Locked)
Stack algorithms: Theorizing an algorithm5m 5s
-
(Locked)
Stack algorithms: Implementing next greater element4m 41s
-
(Locked)
Stack algorithms: Matching parentheses6m 1s
-
(Locked)
Solution: evaluate reverse polish notation4m 27s
-
-
-
-