栈与队列--获取栈顶/队首数据(并出栈/队)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z861269429/article/details/51774296

数组栈
完成ElemType Top(Stack S)函数,该函数把返回栈顶数据(不出栈),已知栈非空。
完成ElemType TopAndPop(Stack S)函数,该函数返回栈顶数据的同时把栈顶数据出栈,已知栈非空。

typedef int ElemType;
struct StackRecord;
typedef struct StackRecord *Stack;
struct StackRecord
{
    int Capacity; //栈容量
    int Top; //栈顶,初始为1
    ElemType *Array;
};

ElemType Top(Stack S)
{
    ElemType x;
    x=S‐>Array[S‐>Top];
    return x;
}
ElemType TopAndPop(Stack S)
{
    ElemType x;
    x=S‐>Array[S‐>Top];
    S‐>Top‐‐;
    return x;
}

链栈
完成ElemType Top(Stack S)函数,该函数返回链栈S的栈顶数据,已知S是带头结点的链栈并且S非空。
完成ElemType TopAndPop(Stack S)函数,该函数把返回链栈S栈顶数据并把栈顶数据出栈,已知S是带头结点的非空链栈。

typedef int ElemType;
struct Node;
typedef struct Node * PtrToNode;
typedef PtrToNode Stack;
struct Node
{
    ElemType data;
    PtrToNode next;
};

ElemType Top(Stack S)
{
    return S‐>next‐>data;
}
ElemType TopAndPop(Stack S)
{
    ElemType x=S‐>next‐>data;
    Stack p=NULL;
    p=S‐>next;
    S‐>next=p‐>next;
    free(p);
    return x;
}

数组队列
完成ElemType Front(Queue Q)函数,该函数返回非空队列Q的队首数据(不出队),其中Q是基于数组的非循环队列。
完成ElemType FrontAndDequeue(Queue Q)函数,该函数返回非空队列Q的队首数据并将队首数据出队,其中Q是基于数组的非循环队列。

typedef int ElemType;
struct QueueRecord;
typedef struct QueueRecord * Queue;
struct QueueRecord
{
    int Capacity; //队列总容量
    int Front; //队首 初始值为0
    int Rear; //队尾,初始值为1
    int Size; //队列中数据数,初始值为0
    ElemType *Array;
};

ElemType Front(Queue Q)
{
    return Q‐>Array[Q‐>Front];
}
ElemType FrontAndDequeue(Queue Q)
{
    Q‐>Front++;
    Q‐>Size‐‐;
    return Q‐>Array[Q‐>Front‐1];
}

链队列
完成ElemType Front(Queue q)函数,该函数返回链表的队列q的队首数据(但不出栈),其中q是不带头节点的非空链表队列。
完成ElemType FrontAndDequeue(Queue q)函数,该函数返回非空队列q的队首数据并将队首数据出队,其中q是不带头节点的链表队列。

typedef int ElemType;
struct node;
typedef struct node Node;
struct queue;
typedef struct queue * Queue;
struct node
{
    ElemType data;
    Node * next;
};
struct queue
{
    Node * front; //队首
    Node * rear; //队尾
    int size; //队列中数据数
};

ElemType Front(Queue q)
{
    return q‐>front‐>data;
}
ElemType FrontAndDequeue(Queue q)
{
    ElemType x;
    node *p=q‐>front;
    q‐>front=p‐>next;
    x=p‐>data;
    free(p);
    q‐>size‐‐;
    return x;
}

猜你喜欢

转载自blog.csdn.net/z861269429/article/details/51774296