소개
이 튜토리얼에서는 C++ 프로그래밍 언어에서 스택의 최대 요소를 찾는 방법을 배우게 됩니다. 스택을 사용하여 최대 요소를 찾는 방법에 대한 단계별 가이드를 제공하고, 각 코드 줄을 자세히 설명합니다.
이 튜토리얼에서는 C++ 프로그래밍 언어에서 스택의 최대 요소를 찾는 방법을 배우게 됩니다. 스택을 사용하여 최대 요소를 찾는 방법에 대한 단계별 가이드를 제공하고, 각 코드 줄을 자세히 설명합니다.
~/project 디렉토리에 main.cpp라는 새 파일을 생성합니다. main.cpp 파일에 필요한 C++ 라이브러리를 포함합니다:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
스택의 최대 요소를 찾는 findMax() 함수와 스택의 요소를 출력하는 show() 함수, 두 가지 함수를 정의합니다.
void findMax(stack<int> s) {
int m = s.top();
int a;
while (!s.empty()) {
a = s.top();
if (m < a)
m = a;
s.pop();
}
cout << "\n\nThe maximum element of the stack is: " << m << endl;
}
void show(stack<int> s) {
while (!s.empty()) {
cout << " " << s.top();
s.pop();
}
cout << endl;
}
main() 함수에서 int 타입의 새로운 스택을 생성하고 push() 메서드를 사용하여 요소를 채웁니다.
show() 함수를 호출하여 스택의 요소를 LIFO (Last-In, First-Out) 순서로 출력합니다.
마지막으로, findMax() 함수를 호출하여 스택에서 최대 요소를 찾습니다.
int main() {
cout << "\n\nWelcome to the Stack Program in C++!\n\n\n";
stack<int> s;
s.push(4);
s.push(2);
s.push(20);
s.push(12);
s.push(52);
s.push(14);
cout << "The elements of the Stack in LIFO order are: ";
show(s);
findMax(s);
return 0;
}
터미널에서 다음 명령을 사용하여 프로그램을 컴파일합니다.
g++ main.cpp -o main && ./main
프로그램의 출력은 다음과 같아야 합니다.
Welcome to the Stack Program in C++!
The elements of the Stack in LIFO order are: 14 52 12 20 2 4
The maximum element of the stack is: 52
이 튜토리얼에서는 C++ 프로그래밍 언어를 사용하여 스택에서 최대 요소를 찾는 방법을 배웠습니다. 이 튜토리얼이 도움이 되었기를 바랍니다!