栈与队列比较与创建

栈处理数据先进后出,进的那一方为栈顶,出数据也在栈顶

实现栈有两种方式,1.数组栈2.链式栈,但是优先选数组栈,因为栈的进出数据只在栈顶

数组栈

typedef struct Stack
{
    STDataType *x;//指向顺序表的头节点
    int top;//栈顶的下标
    int capacity;//顺序表的容量
}
//栈的初始化
void STInit(ST *pst)
{
    assert(pst);
    pst->x=NULL;
    pst->top=0;//初始化为0,那么实际的栈顶下标位置为top-1,比如top=0时,实际上栈顶在-1的位置上,顺序表无有效数据
    pst->capacity=0;
}

//栈的销毁
void STDestory(ST*pst)
{
    assert(pst);
    free(pst->x);
    pst->x=NULL;
    pst->capacity=pst->top=0;
}

//顺序表判空,如果顺序表为空,返回1,非空返回0
void STEmpty(ST *pst)
{
    assert(pst);
    return pst->top==0;
}

//进栈
void STPush(ST *pst,STDataType x)
{
    assert(pst);
    //判断是否增加顺序表容量
    if(pst->capacity==pst->top)
    {
         int newcapacity=pst->capacity==0?4:2*pst->capacity;
         STDataType *tmp=(STDataType *)realloc(sizeof(STDataType)*newcapacity);
        if(tmp==NULL)
        {
            perror("realloc");
            exit(-1);
        }
        pst->capacity=newcapacity;
        pst->x=tmp;
    }

   pst->x[pst->top]=x;
    pst->top++;
}

//出栈
void STPop(St *pst)
{
    assert(pst);
    assert(!STEmpty(pst));//顺序表不能为空
    pst->top--;
}

//获取栈顶元素
STDataType STTop(ST *pst)
{
    assert(pst);
    assert(!STEmpty(pst));
    return pst->x[pst->top-1];
}

队列处理数据先入后出,入数据的一段为队尾,出数据的一端为队头

跟栈一样,队列实现有两种方式,1.数组队列2.链式队列,优先选链式结构,因为涉及到尾插和头插

//节点类型
typedef struct QueueNode
{
    QDataType data;
    struct QueueNode *next;
    
}  QNode;

//链表定义
typedef struct Queuelist
{
    QNode *phead;//链表头节点
    QNode *ptail;//链表尾节点
    int size;//链表的节点数目
}Queue;
//队列初始化
void QueueInit(Queue *q)
{
    assert(q);
    q->phead=q->ptail=NULL;
    q->size=0;
}

//队尾入栈
void QueuePush(Queue *q,QDataType data)
{
    assert(q);
    QNOde *tmp=(QNode *)malloc(sizeof(QNode));
    if(tmp==NULL)
    {
        perror("malloc");
        exit(-1);
    }
    tmp->next=NULL;
    tmp->data=data;
    //如果链表没有节点
    if(q->phead==q->ptail)//如果链表为空,那么phead和ptail指向的节点都为空指针
    {
        q->ptail=q->phead=tmp;
    }
    else
    {
        q->ptail->next=tmp;
        q->ptail=tmp;
    }
    q->size++;
}

//判空
int QueueEmpty(Queue *q)
{
    assert(q);
    return q->size==0;
}

//队头出栈
void QueuePop(Queue *q)
{
    assert(q);
    assert(!QueueEmpty(q));
    //链表内只有一个节点,还需要处理一下尾节点
    if(q->phead->next==NULL)
    {
       free(q->phead);
        q->phead=q->ptail=NULL;
    }
    //链表里有多个节点
    else
    {
    QNOde*tmp=q->phead->next;
    free(q->phead);
    q->phead=tmp;
    }
    q->size--;
}


//获取队头元素
QDataType QueueFront(Queue *q)
{
    assert(q);
    assert(!QueueEmpty(q));
    return q->phead->data;
} 

//获取队尾元素
QDataType QueueBack(Queue *q)
{
    assert(q);
    assert(!QueueEmpty(q));
    return q->ptail->data;
} 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值