单链表的建立和打印

#include <stdio.h>
#include <stdlib.h>

//定义链表数据结构
struct node 
{
    int num;
    struct node *next;
};

//函数声明
struct node *creat(struct node *);
void print(struct node *);

void main()
{
    struct node *head;
    head = NULL;        //创建一个空表
    head = creat(head); //创建单链表
    print(head);        //打印单链表
}


struct node *creat(struct node *head)
{
    struct node *p1,*p2;
    int i = 1;
    //利用malloc函数向系统申请节点
    p1 = p2 = (struct node *)malloc(sizeof(struct node)); //申请节点
    printf("输入大于0的值,小于等于0则结束,值的存放地址为:p1_addr = %d\n",p1);
    scanf("%d",&p1->num);
    p1->next = NULL;

    while(p1->num > 0)
    {
        if(head == NULL)
            head = p1;
        else
            p2->next = p1;
        p2 = p1;

        p1 = (struct node *)malloc(sizeof(struct node));
        p1->next = NULL;//置空
        i++;
        printf("输入大于0的值,小于等于0则结束,值的存放地址为:p%d_addr = %d\n",i,p1);
        scanf("%d",&p1->num);
    }

    free(p1); 
    p1 = NULL;
    p2->next = NULL;
    printf("输入结束\n");
    return head;
}

void print(struct node *head)
{

    struct node *tmp;

    tmp = head;

    printf("链表打印开始!!!\n");
    while(tmp != NULL)
    {
        printf("输入的值为:num = %d,地址为:addr = %d\n",tmp->num,tmp);
        tmp = tmp->next;
    }
    printf("链表打印结束!!!\n");
}

运行结果: 
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weibo1230123/article/details/82783864