数据结构---堆栈

#include<stdio.h>
#include<stdlib.h>
#define MAX 1000

void myPush(int *stack,int *ptr,int data)
{
    stack[++(*ptr)]=data;//如果写成stack[(*ptr)++]=data错误
}

int readMyStack(int *stack,int *ptr)
{
    return stack[*ptr];
}
void myPop(int *ptr)
{
    (*ptr)--;
}

int main()
{
    int mystack[MAX];
    int pointer=-1,i;
    myPush(mystack,&pointer,11);
    myPush(mystack,&pointer,10);
    myPush(mystack,&pointer,9);
    i=readMyStack(mystack,&pointer);
    printf("%d\n",i);
    myPop(&pointer);
    i=readMyStack(mystack,&pointer);
    printf("%d\n",i);
}

  以上为为用数组模拟的传pointer地址的

注意:myStack为指向int值的指针,函数传参,int *stack,stack也为指向int值的指针,向函数传递数组信息,stack[]直接操作数组

/*传pointer值*/
#include<stdio.h>
#include<stdlib.h>
#define MAX 1000

int myPush(int *stack,int ptr,int data)
{
    stack[++(ptr)]=data;
    return ptr;
}

int readMyStack(int *stack,int ptr)
{
    return stack[ptr];
}
int  myPop(int ptr)
{
    return (--ptr);
}

int main()
{
    int mystack[MAX];
    int pointer=-1,i;
    pointer=myPush(mystack,pointer,11);
    pointer=myPush(mystack,pointer,10);
    pointer=myPush(mystack,pointer,9);
    i=readMyStack(mystack,pointer);
    printf("%d\n",i);
    pointer=myPop(pointer);
    i=readMyStack(mystack,pointer);
    printf("%d\n",i);
}

  以上为用传值的方式

/*传结构*/
#include<stdio.h>
#include<stdlib.h>
#define MAX 1000
struct myStack{
    int pointer;
    int stack[MAX];
};

void myPush(struct myStack *s,int ptr,int data)
{
    s->pointer++;
    s->stack[s->pointer]=data;
}

int readMyStack(struct myStack *s,int ptr)
{
    return s->stack[s->pointer];
}
int  myPop(int ptr)
{
    return (--ptr);
}

int main()
{
    int i;
    struct myStack s1;
    s1.pointer=-1;
    myPush(&s1,s1.pointer,11);
    myPush(&s1,s1.pointer,10);
    myPush(&s1,s1.pointer,9);
    i=readMyStack(&s1,s1.pointer);
    printf("%d\n",i);
    s1.pointer=myPop(s1.pointer);
    i=readMyStack(&s1,s1.pointer);
    printf("%d\n",i);
}

  以上为传结构指针的方式

posted @ 2015-05-02 11:22  Gabyler  阅读(324)  评论(0编辑  收藏  举报