C语言 堆栈的压栈与退栈

来源:互联网 发布:网际直通车网络错误 编辑:程序博客网 时间:2024/05/22 15:51

 

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

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

测试:

[root@localhost Gcc]# ./a.out
Enter a number n : 10
  51  89  62  79  40  61  38  18  17  50
  50  17  18  38  61  40  79  62  89  51
[root@localhost Gcc]# ./a.out
Enter a number n : 20
  10  94  73  86  10  74  19  42  88  21  35  75  67  49  51  44  86  12  81   7
   7  81  12  86  44  51  49  67  75  35  21  88  42  19  74  10  86  73  94  10

0 0
原创粉丝点击