您的位置:首页 > 编程语言 > C语言/C++

C语言--单链表之调用输出函数

2014-11-17 17:27 211 查看
# include <stdio.h>

# include <stdlib.h>

# include <time.h>

typedef struct chain

{

        int data;

        struct chain *next;

} list;

list *create()

{

        int i ,n ;

        list *head , *tail ,*p;

        head = tail = NULL;

        printf("Enter a number n : ");

        scanf("%i",&n);

        srand((unsigned)time(NULL));

      for (i = 0 ;i <= n ;i++)

        {

                p = (list*)malloc(sizeof(list));

                p->data = rand()%100 +1;

                if ( head == NULL)

                        head = tail = p;

                else

                        tail = tail->next;

                tail->next = p;

        }

        return head;

}

void print_list(list *head)

{

        list *p,*q;

        p = head;

        while(p)

        {

                printf("%4i",p->data);

                q = p->next;

                free(p);

                p=q;

        }

        printf("\n");

}

int main (void)

{

        list *head;

        head=create();

        print_list(head);

        return 0;

}

 

测试:

[root@localhost Gcc]# ./alg1-4

Enter a number n : 10

   7  61  81  81  14  69  91  88   8  22

[root@localhost Gcc]# ./alg1-4

Enter a number n : 6

  90  33  77  83  53  72

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: