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


Description

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


Input

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


Output

输出这组整数。


Sample
Input

8
12 56 4 6 55 15 33 62


Output

12 56 4 6 55 15 33 62


Hint

不得使用数组!


一定要知道链表是怎样连接的,并且在做提前先想好要怎样连接,本题是顺序链接只要开一个头结点,在在结尾一个一个连上就行了

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;

};

int main()
{
    struct node *head,*p,*q;
    head = (struct node *)malloc(sizeof(struct node));
    head->next = NULL;
    /*开一个头节点,并在下面再让一个指针只想头结点并用它做游动指针,
    注意头指针很重要,不要轻易去动头指针*/
    q = head;
    int n;
    scanf("%d",&n);
    while(n--) //建立链表;
    {
        p = (struct node *)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next = NULL;  //开一个节点并放入数据,注意新开节点,指针定义为空;
        q->next = p;//“q”为游动指针,即为只向最后一个的指针,也可以在定义一个专门指向尾结点的指针;
        q = p; //每一次游动指针向后移动一位;
    }

    q = head->next; //输出链表;
    while (q!=NULL)
    {
        if(q->next!= NULL)
            printf("%d ",q->data);
        else printf("%d\n",q->data);
        q = q->next;
    }
    return 0;

}
发布了136 篇原创文章 · 获赞 95 · 访问量 2322

猜你喜欢

转载自blog.csdn.net/zhangzhaolin12/article/details/103949858