数据结构(c环境下)

对正整数n,从个位到最高位依次求出其各位数字,并按照求出的先后次序入队,最好将该队列中的所有元素出队,从而反序输出这个整数n的各位数字。

大体思路:先写出队列的相关定义及其入队、出队和判断队空等运算,然后写出函数void seek_n(int n),该函数求n的各位数字,在其函数中需要调用队列的相关函数

#include<stdio.h>
#include<stdlib.h>
#define QElemType int
#define Status int
#define MAXSIZE 100 //队列最大长度
typedef struct {
    QElemType *base;
    int front;
    int rear;
}SqQueue;
//头指针Q.front指向队列第一个元素,尾指针Q.rear指向最后一个元素的下一位置

Status InitQueue(SqQueue &Q){
    Q.base = (QElemType*)malloc(MAXSIZE*sizeof(QElemType));
    Q.front = Q.rear = 0;
    return 1;
}
Status EmptyQueue(SqQueue Q){
    if (Q.front==Q.rear) return 1;
    else return 0;
}
Status QueueLength(SqQueue Q){
    return (Q.rear-Q.front+MAXSIZE)%(MAXSIZE);//如果rear追上front,二者相等,这个公式就出错;并且也无法出现长度为MAXSIZE的情况
    //所以浪费front前面的一个位置,如果rear出现在front前面一个位置就判定队列满,即:
    //数据入队前判断:
    //如果(Q.rear+1)%MAXSIZE==Q.front则队列满。扩展队列再入队。

    //判断队列为空则是:Q.front==Q.rear
}
Status EnQueue(SqQueue &Q, QElemType e){
    if((Q.rear+1)%MAXSIZE==Q.front)
        Q.base = (QElemType*)realloc(Q.base,MAXSIZE*sizeof(QElemType));
    Q.base[Q.rear] = e;
    Q.rear = (Q.rear+1)%MAXSIZE;
    return 1;
}
Status DeQueue(SqQueue &Q, QElemType &e){
    if(Q.front==Q.rear) return 0;
    e = Q.base[Q.front];
    Q.front = (Q.front+1)%MAXSIZE;
    return 1;
}
void seek_n(int n){
    SqQueue Q;
    InitQueue(Q);
    while (n!=0){
        EnQueue(Q,n%10);
        n /= 10;
    }
    int e;
    while (!EmptyQueue(Q)){
        DeQueue(Q,e);
        printf("%d",e);
    }
};
int main(){
    int n;
    scanf("%d",&n);
    seek_n(n);
    return 1;
}

 

C和C++完整教程:https://blog.csdn.net/it_xiangqiang/category_10581430.html
C和C++算法完整教程:https://blog.csdn.net/it_xiangqiang/category_10768339.html