C语言 堆栈的建立

来源:互联网 发布:金山软件总公司怎么样 编辑:程序博客网 时间:2024/05/17 09:33

# include <stdio.h>
# include <stdlib.h>
# include <time.h>
struct chain
{
        int data;
        struct chain *next;
};
struct chain *push(int n,  int *data1)
{
        struct chain *top,*s;
        top=NULL;
        int i;
        for ( i =0;i<n;i++)
        {
        s = (struct chain *)malloc(sizeof(struct chain));
        s->data = data1[i];
        s->next = top;
        top =s ;
        }
        return top;
}

int main (void)
{
int n,i;
struct chain *p;
printf("Enter a number n : ");
scanf("%i",&n);
srand((unsigned)time(NULL));
int a[n];
for (i=0;i<n;i++)
        a[i]=rand()%100+1;
for (i=0;i<n;i++)
        printf("%4i",a[i]);
printf("\n");
p = push(n,a);
while (p!=NULL)
{
        printf("%4i",p->data);
        p=p->next;
}
printf("\n");
return 0;
}
                

测试:

[root@localhost Gcc]# ./a.out
Enter a number n : 10
  40  52  85  34  94  41  81  33   4  92
  92   4  33  81  41  94  34  85  52  40
[root@localhost Gcc]# ./a.out
Enter a number n : 20
  18  95  61  88  74  87  79  18  82  95  14  79  23   2  52   6  62  74  25   5
   5  25  74  62   6  52   2  23  79  14  95  82  18  79  87  74  88  61  95  18

0 0