[数据结构]栈与队列

1.2 栈和队列

1.2.1 用数组仿真堆栈

#include"stdio.h"
#define MaxSize 10
int stack[MaxSize];
int top=-1;
void push(int value)
{
    int i;
    if(top>=MaxSize)
        printf("\nThe stack is full!\n");
    else
        {
            printf("\nThe stack content before(top->bottom):");
            for(i=top;i>=0;i--)
                printf("[%d]",stack[i]);
            top++;
            stack[top]=value;
            printf("\nThe stack content after push(top->bottom):");
            for(i=top;i>=0;i--)
                printf("[%d]",stack[i]);
            printf("\n");
        }
}
int pop()
{
    int temp;
    int i;
    if(top<0)
        {
            printf("\nThe stack is empty!\n");
            return -1;
        }
        printf("\nThe stack content before(top->bottom):");
        for(i=top;i>=0;i--)
            printf("[%d]",stack[i]);
        temp=stack[top];
        top--;
        printf("\nThe pop value is [%d]",temp);
        printf("\nThe stack content after pop(top->bottom):");
        for(i=top;i>=0;i--)
                printf("[%d]",stack[i]);
            printf("\n");
        return temp;
}
int main()
{
    int select;
    int stack[5];
    int i,value;
    printf("\n(1)Input a stack data");
    printf("\n(2)Output a stack data");
    printf("\n(3)Exit");
    printf("\nPlease select one=>");
    scanf("%d",&select);
    do
    {
        switch(select)
        {
            case 1:printf("\nPlease input the data=>");
            scanf("%d",&value);
            push(value);
            break;
            case 2:value=pop();
            break;
        }
        printf("\n(1)Input a stack data");
        printf("\n(2)Output a stack data");
        printf("\n(3)Exit");
        printf("\nPlease select one=>");
        scanf("%d",&select);
        printf("\n");
    }while(select!=3);
    return 0;
}

运行结果

1.2.2 用链表仿真堆栈

#include <malloc.h>
#include"stdio.h"
struct s_node
{
    int data;
    struct s_node *next;
};
typedef struct s_node s_list;
typedef    s_list *link;
link stack=NULL;
void print_stack()
{
    link temp=NULL;
    temp=stack;
    if(temp==NULL)
        printf("The stack is empty!\n");
    else
    {
        while(temp!=NULL)
        {
            printf("[%d]",temp->data);
            temp=temp->next;
        }
        printf("\n");
    }
}
void push(int value)
{
    link newnode;
    printf("\nThe stack content before(top->bottom):");
    print_stack();
    newnode=(link)malloc(sizeof(s_list));
    newnode->data=value;
    newnode->next=stack;
    stack=newnode;
}
int pop()
{
    link top;
    int temp;
    printf("\nThe stack content before(top->bottom):");
    print_stack();
    if(stack!=NULL)
    {
        top=stack;
        stack=stack->next;
        temp=top->data;
        free(top);
        return temp;
    }
    else
        return -1;
}
int main()
{
    link point;
    int select;
    int i,value;
    printf("\n(1)Input a stack data");
    printf("\n(2)Output a stack data");
    printf("\n(3)Exit");
    printf("\nPlease select one=>");
    scanf("%d",&select);
    do
    {
        switch(select)
        {
            case 1:printf("\nPlease input the data=>");
                scanf("%d",&value);
                push(value);
                printf("\nThe stack content current(top->bottom):");
                print_stack();
                break;
            case 2:value=pop();
                printf("\nThe output value is [%d]",value);
                printf("\n");
                printf("The stack content currnet(top->bottom):");
                print_stack();
                break;
        }
        printf("\n(1)Input a stack data");
        printf("\n(2)Output a stack data");
        printf("\n(3)Exit");
        printf("\nPlease select one=>");
        scanf("%d",&select);
    }while(select!=3);
    return 0;
}

运行结果

1.2.3 顺序栈公用

#include "stdio.h"
#define MEMORY_SIZE  100  /* 内存大小 */
#define MAX_STACKS 10      /* 栈的个数加1*/
typedef char element;
element memory [MEMORY_SIZE];
int top[MAX_STACKS-1];
int boundary[MAX_STACKS];
/* 置栈空*/
void Initial(int n)
{/*将各个顺序栈置空*/
    int i;
    top [0] = boundary [0] = -1;
    for ( i =1;  i<n;  i ++ )
        top[i]=boundary[i]= (MEMORY_SIZE/n)*i;
    boundary[n]=MEMORY_SIZE-1;
}
/*进栈*/
void Push(int i, element item)
{
    if (top[i] == boundary[i+1] )
    {
        printf("第%d个栈已满。",i);
    }
    memory[++top[i]] = item;
}
/*退栈*/
element Pop(int i)
{
    if ( top[i] == boundary[i] )
    {
        printf("第%d个栈已空。",i);
    }
    return memory[top[i]--];
}
int main()
{
    int  n=2;      /* 使用的栈的个数 */
    element first,sec;
    Initial(n);
    Push(1,'a');
    Push(0,'b');
    sec=Pop(1);
    first=Pop(0);
    return 0;
}

1.2.4 进制转换问题

#include "stdio.h"
#include "stdlib.h"
#define StackSize 100 /*假定预分配的栈空间最多为100个元素*/
typedef int DataType;/*假定栈元素的数据类型为字符*/
typedef struct{
      DataType data[StackSize];
      int top;
}SeqStack;
/* 置栈空*/
void Initial(SeqStack *S)
{/*将顺序栈置空*/
      S->top=-1;
}
/*判栈空*/
int IsEmpty(SeqStack *S)
{
    return S->top==-1;
}
/*判栈满*/
int IsFull(SeqStack *S)
{
    return S->top==StackSize-1;
}
/*进栈*/
void Push(SeqStack *S,DataType x)
{
    if (IsFull(S))
    {
        printf("栈上溢"); /*上溢,退出运行*/
        exit(1);
    }
    S->data[++S->top]=x;/*栈顶指针加1后将x入栈*/
}
/*出栈*/
DataType Pop(SeqStack *S)
{
    if(IsEmpty(S))
    {
        printf("栈为空"); /*下溢,退出运行*/
        exit(1);
    }
    return S->data[S->top--];/*栈顶元素返回后将栈顶指针减1*/
}
/* 取栈顶元素*/
DataType Top(SeqStack *S)
{
    if(IsEmpty(S))
    {
        printf("栈为空"); /*下溢,退出运行*/
        exit(1);
    }
    return S->data[S->top];
}
void MultiBaseOutput (int N,int B)
{/*假设N是非负的十进制整数,输出等值的B进制数*/
    int i;
    SeqStack S;
    Initial(&S);
    while(N){  /*从右向左产生B进制的各位数字,并将其进栈*/
        Push(&S,N%B); /*将bi进栈0<=i<=j*/
        N=N/B;
    }
    while(!IsEmpty(&S)){  /*栈非空时退栈输出*/
        i=Pop(&S);
        printf("%d",i);
    }
}
int main()
{
    MultiBaseOutput(1023,2);
    return 0;
}

运行结果

1.2.5 顺序队列操作

#include "stdio.h"
#include "stdlib.h"
#define QueueSize 100 /*假定预分配的队列空间最多为100个元素*/
typedef int DataType;/*假定队列元素的数据类型为字符*/
typedef struct{
      DataType data[QueueSize];
      int front;/*头指针*/
      int rear;/*尾指针*/
}SeqQueue;
/* 置队列空*/
void Initial(SeqQueue *Q)
{/*将顺序队列置空*/
      Q->front=Q->rear=0;
}
/*判队列空*/
int IsEmpty(SeqQueue *Q)
{
    return Q->front==Q->rear;
}
/*判队列满*/
int IsFull(SeqQueue *Q)
{
    return Q->rear==QueueSize-1+Q->front;
}
/*进队列*/
void Push(SeqQueue *Q,DataType x)
{
    if (IsFull(Q))
    {
        printf("队列上溢"); /*上溢,退出运行*/
        exit(1);
    }
    Q->data[Q->rear++]=x;/*队列顶指针加1后将x入队列*/
}
/*出队列*/
DataType Pop(SeqQueue *Q)
{
    if(IsEmpty(Q))
    {
        printf("队列为空"); /*下溢,退出运行*/
        exit(1);
    }
    return Q->data[Q->front++];/*队列顶元素返回后将队列顶指针减1*/
}
/* 取队列顶元素*/
DataType Top(SeqQueue *Q)
{
    if(IsEmpty(Q))
    {
        printf("队列为空"); /*下溢,退出运行*/
        exit(1);
    }
    return Q->data[Q->front];
}

int main()
{
    SeqQueue s;
    DataType first,sec;
    Initial(&s);
    Push(&s,'a');
    Push(&s,'b');
    first=Top(&s);
    Pop(&s);
    sec=Top(&s);
    Pop(&s);
    return 0;
}

1.2.6 循环队列

#include "stdio.h"
#include "stdlib.h"
#define QueueSize 100 /*假定预分配的队列空间最多为100个元素*/
typedef int DataType;/*假定队列元素的数据类型为字符*/
typedef struct{
    DataType data[QueueSize];
    int front;/*头指针*/
    int rear;/*尾指针*/
    int count; /*计数器,记录队中元素总数*/
}CirQueue;
/* 置队列空*/
void Initial(CirQueue *Q)
{/*将顺序队列置空*/
    Q->front=Q->rear=0;
    Q->count=0;     /*计数器置0*/
}
/* 判队列空*/
int IsEmpty(CirQueue *Q)
{
    return Q->front==Q->rear;
}
/*判队列满*/
int IsFull(CirQueue *Q)
{
    return Q->rear==QueueSize-1+Q->front;
}
/*进队列*/
void EnQueue(CirQueue *Q,DataType x)
{
    if (IsFull(Q))
    {
        printf("队列上溢"); /*上溢,退出运行*/
        exit(1);
    }
    Q->count ++;                        /*队列元素个数加1*/
    Q->data[Q->rear]=x;                 /*新元素插入队尾*/
    Q->rear=(Q->rear+1)%QueueSize;      /*循环意义下将尾指针加1*/
}
/*出队列*/
DataType DeQueue(CirQueue *Q)
{
    DataType temp;
    if(IsEmpty(Q))
    {
        printf("队列为空"); /*下溢,退出运行*/
        exit(1);
    }
    temp=Q->data[Q->front];
    Q->count--;                        /*队列元素个数减1*/
    Q->front=(Q->front+1)&QueueSize;   /*循环意义下的头指针加1*/
    return temp;

}
/* 取队列顶元素*/
DataType Front(CirQueue *Q)
{
    if(IsEmpty(Q))
    {
        printf("队列为空"); /*下溢,退出运行*/
        exit(1);
    }
    return Q->data[Q->front];
}

int main()
{
    CirQueue s;
    DataType first,sec;
    Initial(&s);
    EnQueue(&s,'a');
    EnQueue(&s,'b');
    first=Front(&s);
    DeQueue(&s);
    sec=Front(&s);
    DeQueue(&s);
    return 0;
}

1.2.7 链队列的入队、出队

#include "stdio.h"
#include "stdlib.h"
#define QueueSize 100 /*假定预分配的队列空间最多为100个元素*/
typedef char DataType ; /*假定队列元素的数据类型为字符*/
typedef struct node{
    DataType data;
    struct node *next;
}QueueNode;
typedef struct{
    QueueNode *front;  /*头指针*/
    QueueNode *rear;
}LinkQueue;
/* 置队列空*/

void Initial(LinkQueue *Q)
/*将顺序队列置空*/

{    Q->front=Q->rear=NULL;
}

/*判队列空*/
int IsEmpty(LinkQueue *Q)
{
    return Q->front==NULL&&Q->rear==NULL;
}

/*进队列*/
void Push(LinkQueue *Q,DataType x)
{
/*将元素x插入链队列尾部*/
    QueueNode *p=(QueueNode *)malloc(sizeof(QueueNode));/*申请新结点*/
    p->data=x;
    p->next=NULL;
    if(IsEmpty(Q))
        Q->front=Q->rear=p;  /*将x插入空队列*/
    else
    { /*x插入非空队列的尾*/
        Q->rear->next=p;     /*p链到原队尾结点后*/
        Q->rear=p;           /*队尾指针指向新的尾*/
    }
}

/*出队列*/
DataType Pop(LinkQueue *Q)
{
    DataType x;
    QueueNode *p;
    if(IsEmpty(Q))
    {
        printf("队列为空");/*下溢*/
        exit(1);
    }
    p=Q->front;                   /*指向对头结点*/
    x=p->data;                    /*保存对头结点的数据*/
    Q->front=p->next;             /*将对头结点从链上摘下*/
    if(Q->rear==p)/*原队中只有一个结点,删去后队列变空,此时队头指针已为空*/
        Q->rear=NULL;
    free(p);   /*释放被删队头结点*/
    return x;  /*返回原队头数据*/
}

/* 取队列顶元素*/
DataType Front(LinkQueue *Q)
{
    if(IsEmpty(Q))
    {
        printf("队列为空"); /*下溢,退出运行*/
        exit(1);
    }
    return Q->front->data;
}

int main()
{
    LinkQueue s;
    DataType first,sec;
    Initial(&s);
    Push(&s,'a');
    Push(&s,'b');
    first=Front(&s);
    Pop(&s);
    sec=Front(&s);
    Pop(&s);
    return 0;
}

1.2.8 舞伴问题

#include "stdio.h"
#include "stdlib.h"
#define MAX_DANCERS 100//最多跳舞人数
#define QueueSize 100 //假定预分配的队列空间最多为100个元素
typedef struct{
    char name[20];
    char sex;  //性别,'F'表示女性,'M'表示男性
}Person;
typedef Person DataType;  //将队列中元素的数据类型改为Person
typedef struct{
    DataType data[QueueSize];
    int front;//头指针
    int rear;//尾指针
    int count; //计数器,记录队中元素总数
}CirQueue;
// 置队列空
void Initial(CirQueue *Q)
{//将顺序队列置空
    Q->front=Q->rear=0;
    Q->count=0;     //计数器置0
}
//判队列空
int IsEmpty(CirQueue *Q)
{
    return Q->front==Q->rear;
}
//判队列满
int IsFull(CirQueue *Q)
{
    return Q->rear==QueueSize-1+Q->front;
}
//进队列
void EnQueue(CirQueue *Q,DataType x)
{
    if (IsFull(Q))
    {
        printf("队列上溢"); //上溢,退出运行
        exit(1);
    }
    Q->count ++;                        //队列元素个数加1
    Q->data[Q->rear]=x;                 //新元素插入队尾
    Q->rear=(Q->rear+1)%QueueSize;      //循环意义下将尾指针加1
}
//出队列
DataType DeQueue(CirQueue *Q)
{
    DataType temp;
    if(IsEmpty(Q))
    {
        printf("队列为空"); //下溢,退出运行
        exit(1);
    }
    temp=Q->data[Q->front];
    Q->count--;                        //队列元素个数减1
    Q->front=(Q->front+1)&QueueSize;   //循环意义下的头指针加1
    return temp;

}
// 取队列顶元素
DataType Front(CirQueue *Q)
{
    if(IsEmpty(Q))
    {
        printf("队列为空"); //下溢,退出运行
        exit(1);
    }
    return Q->data[Q->front];
}
void DancePartner(Person dancer[],int num)
{//结构数组dancer中存放跳舞的男女,num是跳舞的人数。
    int i;
    Person p;
    CirQueue Mdancers,Fdancers;
    Initial(&Mdancers);//男士队列初始化
    Initial(&Fdancers);//女士队列初始化
    for(i=0;i<num;i++){//依次将跳舞者依其性别入队
        p=dancer[i];
        if(p.sex=='F')
            EnQueue(&Fdancers,p);   //排入女队
        else
            EnQueue(&Mdancers,p);   //排入男队
    }
    printf("dance queue is:\n");
    while(!IsEmpty(&Fdancers)&&!IsEmpty(&Mdancers)){
        //依次输入男女舞伴名
        p=DeQueue(&Fdancers);     //女士出队
        printf("%s        ",p.name);//打印出队女士名
        p=DeQueue(&Mdancers);     //男士出队
        printf("%s\n",p.name);    //打印出队男士名
    }
    if(!IsEmpty(&Fdancers)){ //输出女士剩余人数及队头女士的名字
        printf("still have %d landy wait next.\n",Fdancers.count);
        p=Front(&Fdancers);  //取队头
        printf("%s will be the first to get a partner. \n",p.name);
    }
    else if(!IsEmpty(&Mdancers)){//输出男队剩余人数及队头者名字
        printf("still have %d man wait next.\n",Mdancers.count);
        p=Front(&Mdancers);
        printf("%s will be the first to get a partner.\n",p.name);
    }
}
void InitialDancer(Person dancer[])
{
    //跳舞报名
}
int main()
{
    Person dancer[MAX_DANCERS];
    int n=93;
    InitialDancer(dancer);
    DancePartner(dancer,93);
    return 0;
}

运行结果

1.2.9 动态堆栈

#include "stdio.h"
#include "stdlib.h"

typedef char datatype;
typedef struct node {
    datatype data;
    struct node *next;
} stack;

int Empty(stack *s) {
    return (s == NULL);
}

stack *creat(void) {
    char ch;
    stack *head;
    stack *p;
    head = NULL;/*初始化为空*/
    ch = getchar();
    while (ch != '\n') {
        p = (stack *) malloc(sizeof(stack));/*分配空间*/
        p->data = ch;/*数据域赋值*/
        p->next = head;/*指定后继指针*/
        head = p;/*head指针指定到新插入的结点上*/
        ch = getchar();
    }
    return (head);
}

void MakeNull(stack *s)/*使栈s为空*/
{
    stack *p = s;
    while (s != NULL) {
        s = s->next;
        free(p);/*释放空间*/
        p = s;
    }
}

datatype Top(stack *s) {
    if (Empty(s))/*s为空栈,直接跳出,提示出错信息*/
        printf("The stack is empty.");
    else
        return s->data;
}

void Pop(stack *s) {
    stack *p;
    if (Empty(s)) /*s为空栈,直接跳出,提示出错信息*/
        printf("The stack is empty.");
    else {
        p = s;
        s = s->next;
        free(p);/*释放栈顶空间*/
    }
}

void Push(stack *s, datatype x) {
    stack *p;
    p = (stack *) malloc(sizeof(stack));
    p->data = x;
    p->next = s;
    s = p;
}

int main() {
    stack *m_stack = creat();
    char m_top;
    if (!Empty(m_stack)) {
        m_top = Top(m_stack);
        Pop(m_stack);
    } else
        Push(m_stack, 'a');
    MakeNull(m_stack);
    return 0;
}

1.2.10 动态队列

#include "stdio.h"
#include "stdlib.h"

typedef char datatype;
typedef struct node {
    datatype data;
    struct node *next;
} position;
typedef struct queue {
    position *front;
    position *rear;
} queuetype;

/*判断是否为空队列:*/
int Empty(queuetype *q) {
    return (q->front == q->rear);
}

/*使队列为空:*/
void MakeNull(queuetype *q) {
    q->rear = q->front;
    while (q->front != NULL) {
        q->front = q->front->next;
        free(q->rear);/*释放空间*/
        q->rear = q->front;
    }
    q->front = (position *) malloc(sizeof(position));
    q->front->next = NULL;
    q->rear = q->front;
}

/* 取队列的队头元素:*/
datatype Front(queuetype *q) {
    if (Empty(q))
        printf("'The queue is empty!");
    else
        return (q->front->next->data);
}

/*删除队列头元素:*/
void dequeue(queuetype *q) {
    position *p;
    if (Empty(q))
        printf("The queue is empty!");
    else {
        p = q->front;
        q->front = q->front->next;
        free(p);
    }
}

/* 在队列中加入新元素:*/
void Enqueue(datatype x, queuetype *q) {
    position *p;
    p = (position *) malloc(sizeof(position));
    p->data = x;
    p->next = NULL;
    q->rear->next = p;
    q->rear = p;
}

int main() {
    queuetype *m_q;
    char m_top;
    m_q = (queuetype *) malloc(sizeof(queuetype));
    m_q->front = m_q->rear = (position *) malloc(sizeof(position));
    m_q->rear->next = NULL;
    if (!Empty(m_q)) {
        m_top = Front(m_q);
        dequeue(m_q);
    } else
        Enqueue('c', m_q);
    MakeNull(m_q);
    return 0;
}
posted @ 2019-11-14 11:09  Xu_Lin  阅读(282)  评论(0编辑  收藏  举报