C语言链表-创建链表并且从键盘输入赋值

链表是C语言里面学习比较困难的一部分内容,下面这个例子就演示了创建一个链表并且从输入端赋值,希望对大家有用。
#include <stdio.h>
#include <stdlib.h>

struct link
{
    int num;
    struct link *next;
};
int main()
{
    int n,i;
    struct link *head,*p;
    printf("How many numbers do you want to input:");
    scanf("%d",&n);
    head=(struct link*)malloc(sizeof(struct link));//创建头结点
    p=(struct link*)malloc(sizeof(struct link));//申请第一个结点
    head->next=p;//链接头结点和首结点
    printf("Please input numbers:\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&p->num);
        p->next=(struct link*)malloc(sizeof(struct link));//申请下一个节点
        p=p->next;//将该节点和下一个节点连起来
    }
    p=head->next;//由于第一个循环已经将链表移到末尾,所以这里要将链表移到首结点开始打印
    for(i=0;i<n;i++)
    {
        printf("%d ",p->num);
        p=p->next;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tangCprogranm/article/details/78156905