【Data Structure Learning Record 6】——Stack Application

1. Base conversion

1. Principle

Because we 除N取余realize the N-ary conversion by the method, and then output the result of the remainder in reverse order. Because it is in reverse order, so yes 后进先出, that is the model of our stack. So we only need to put the result of each remainder into the stack, and finally output all, to complete our base conversion.
Then give a 10转Nhexadecimal program (0<N<=36).

2. Code implementation

Because this part of the code is relatively simple, so we directly use the array to simulate the stack:

#include <stdio.h>

int main()
{
    
    
    int number;
    int stack[32];
    int top = 0;
    int N;

    scanf("%d %d", &number, &N);
    while(number > 0)
    {
    
    
        ++top;
        stack[top] = number % N;
        number /= N;
    }
    while(top > 0)
    {
    
    
	    if (stack[top] > 9)
        {
    
    
            printf("%c", stack[top]-10+'A');
        }
        else
        {
    
    
            printf("%c", stack[top]+'0');
        }
        --top;
    }
    printf("(%d)\n", N);

    return 0;
}

2. Expression evaluation

Ah, this, I want to talk about it together with queues, because there is no application for queues in the book. So I put this question in the queue and stack to talk about it together.

Guess you like

Origin blog.csdn.net/u011017694/article/details/109387557