2014年11月

    什么是栈?先进后出/后进先出为栈。与队列相反。就是先来的要排到最后,后来的却可以先走。栈最早是由图灵奖命名来源者图灵发明,最初为解决程序的调用和返回。而栈的应用之一就是递归。

#include <stdio.h>

void stack(int top, int *ranks);

int main(){

    int ranks[100] = {4,5,0,6,8,1,3,9,7,2};

    //栈顶

    int top = 9;

    stack(top, ranks);

}

void stack(int top, int *ranks){

    char more = '\0';

    int new = 0;

    while(top >= 0){

        printf("----------------%d-------------------\n", ranks[top]);

        top--;

        printf("Add Element?[y/n] \n");

        scanf(" %c", &more);

        if(more == 'y'){

            printf("New Number:\n");

            scanf(" %d", &new);

            ranks[++top] = new;

        }

    }

}

    什么是队列?队列就是先进先出,也就是现实生活中我们的排队,先来的先走,后来的后走,一个接一个,这就是队列。队列优点很明显,按照顺序谁也不抢。缺点也很明显,如果排头的走了,那么第二个要排头,第三个要到第二个,每个都要前进一步,对计算机来讲这就是资源的损耗。队列也称为FIFO,就是First In, First Out.

    下面是队列的基本模型。我们有一个现成的队伍,数组ranks。然后出一个,head是指向队头的指针就加1,新来一个,就在队尾的后一个位置tail指向的位置存放,然后tail也加1。这样可以避免每出队一次,就要全部前移一次。

#include <stdio.h>

void queue(int head, int tail, int *ranks);

int main(){

    int ranks[100] = {4,5,0,6,8,1,3,9,7,2};

    int head = 0;

    int tail = 10;

    queue(head, tail, ranks);

}

void queue(int head, int tail, int *ranks){

    char more = '\0';

    int new = 0;

    while(head < tail){

        printf("----------------%d-------------------\n", ranks[head]);

        head++;

        printf("Add Element?[y/n] \n");

        scanf(" %c", &more);

        if(more == 'y'){

            printf("New Number:\n");

            scanf(" %d", &new);

            ranks[tail] = new;

            tail++;

        }

    }

}