数据结构实验之链表一:顺序建立链表 SDUT OJ C语言 2116

数据结构实验之链表一:顺序建立链表

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。

Input

第一行输入整数的个数N;
第二行依次输入每个整数。

Output

输出这组整数。

Sample Input

8
12 56 4 6 55 15 33 62

Sample Output

12 56 4 6 55 15 33 62
#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
}    s;//链表是把结点连接起来,首先建立链表的结点,里面存放数据域和指针域
struct node *creat(int n)
{
    int i;
    struct node *head,*p,*tail;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;
    tail=head;//申请一个头节点让它为空,让尾指针指向
    for(i=1; i<=n; i++)
    {
        p=(struct node *)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next=NULL;//p现在是一个存放了数据和指针的结点
        tail->next=p;//要把p连接在链表中就要把p连接在尾结点之后,要连接尾结点和p,如果想要把尾结点和p连接在一起,那就要把p的地址记下来,用tail记p的地址,就是tail->next=p,这样就把p的地址记下来了,
        tail=p; //连接起新的链表之后,就需要把尾结点放在最后,tail=p
    }
    return head;
};
void print(struct node *head)
{
    int n=0;
    struct node *p;
    p=head->next;
    while(p)//只要p不为空
    {
        n++;
        if(n==1)
            printf("%d",p->data);
        else
            printf(" %d",p->data);//输出p所保存的数据,输出结束后指向下一个
        p=p->next;
    }
    printf("\n");//n保证空格数量完全一致
}
int main()
{
    int n;
    scanf("%d",&n);
    struct node *head;
    head=creat(n);
    print(head);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40354578/article/details/81352647