본문 바로가기

programming/C, C++, C#

[CPP] Queues and Stacks (30 days of learn)



> Quest.

Write the following declarations and implementations:

Two instance variables: one for your , and one for your .

A void pushCharacter(char ch) method that pushes a character onto a stack.

A void enqueueCharacter(char ch) method that enqueues a character in the  instance variable.

A char popCharacter() method that pops and returns the character at the top of the  instance variable.

A char dequeueCharacter() method that dequeues and returns the first character in the  instance variable.



> Input.

Input Format

You do not need to read anything from stdin. The locked stub code in your editor reads a single line containing string . It then calls the methods specified above to pass each character to your instance variables.

Constraints

 is composed of lowercase English letters.



> Output.

Output Format

You are not responsible for printing any output to stdout. 

If your code is correctly written and  is a palindrome, the locked stub code will print 

The word, s, is a palindrome.; otherwise, it will print The word, s, is not a palindrome. 



> solve

*차후 큐와 스택, 데크와 관련된 설명을 추가하겠습니다.


문제는 단순합니다. 

큐와 스택에 각각의 문자열을 저장합니다.

큐와 스택이 출력시 같은 문자를 계속 뱉고 끝나면 palindrome .

하나라도 다르면 is not a palindrome. 추가로 출력하면 됩니다.


palindrome : 회문(回文: madam이나 nurses run처럼 앞에서부터 읽으나 뒤에서부터 읽으나 동일한 단어나 구)


#include <iostream>

using namespace std;

class Solution {
    public:
        int top = 0;
        char *s_data = (char *) malloc (sizeof(char) *top);
        void pushCharacter(char cost){
            // 특정 수량이 정해져있다면 오버플로우 제어 필요.
            top++;
            s_data = (char *) realloc (s_data, sizeof(char) *top);
            *(s_data+top) = cost;
        };
        char popCharacter(){
            if( top <= 0 ){
                cout<<"언더플로우!";
            }
            char result = *(s_data+top);
            top--;
            return result;
        };
    
        int start=0, end = 0;
        char *q_data = (char *) malloc (sizeof(char) *(end - start));
        void enqueueCharacter(char cost){
            // 특정 수량이 정해져있다면 오버플로우 제어 필요.
            end++;
            q_data = (char *) realloc (q_data, sizeof(char) *(end - start));
            *(q_data+end) = cost;
        };
        int dequeueCharacter(){
            if( start >= end ){
                cout<<"언더플로우!";
            }
            start++;
            char result = *(q_data+start);
            return result;
        };
};


문제에는 입력값 때문에 불필요한 언더플로우 처리를 하였습니다. 차라리 이 부분은 exception 처리를 해도 좋을 것 같습니다.


* 실행이 되는 메인부분은 제가 작성한 코드가 아니므로 원문 링크를 참조해 주세요!




반응형

'programming > C, C++, C#' 카테고리의 다른 글

[C#] DLL 가져오기  (0) 2019.05.26
[C#] 프로젝트 절대 경로  (0) 2019.05.26
[CPP] Generics  (0) 2017.10.09