创建链表(一)

一,创建链表结构带有头节点的链表

/*************************************************************************
    > File Name: 111单链表.c
    > Author: songli
    > QQ: 2734030745
    > Mail: 15850774503@163.com
        > CSDN: http://my.csdn.net/Poisx
    > github: https://github.com/chensongpoixs
    > Created Time: Thu 24 Aug 2017 05:38:09 AM PDT
 ************************************************************************/

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

struct LNode
{
    int data;
    struct LNode * next;
};

struct LNode *create(int n)
{
    int i;
    struct LNode *head, *p1, *p2 = NULL; //VS编译器中指针要初始化 gcc 编译器已经优化过了
    int a;
    head = NULL;  //头节点为NULL
    printf("Input the integers:\n");
    for (i = n; i > 0; --i)
    {
        //分配空间
        p1 = (struct LNode*)malloc(sizeof(struct LNode)); 
        //输入数据
        scanf("%d", &a);
        p1->data = a; //数据域赋值
        //指定头结点
        if (head == NULL)
        {
            head = p1;  //把p1 付给头结点
            p2 = p1;  //第一
        }
        else 
        {
            p2->next = p1;
            p2 = p1;
        }
    }
    p2->next = NULL;
    return head;
}

int main(int argc, char *argv[])
{
    int n;
    struct LNode *q;
    printf("Input the count of the nodes you want to creat:");
    scanf("%d", &n);
    q = create(n);
    printf("The result is :\n");
    while (q)
    {
        printf("%d ", q->data);
        q = q->next;
    }    

    return 0;
}

github的链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值