逆序建立链表

数据结构实验之链表二:逆序建立链表

Description
输入整数个数N,再输入N个整数,按照这些整数输入的相反顺序建立单链表,并依次遍历输出单链表的数据。
Input
第一行输入整数N;;
第二行依次输入N个整数,逆序建立单链表。
Output
依次输出单链表所存放的数据。
Sample
Input

10
11 3 5 27 9 12 43 16 84 22

Output
22 84 16 43 12 9 27 5 3 11

第一种:

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};
int main()
{
    int i,n;
    struct node *head,*p;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        p=(struct node *)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next=head->next;
        head->next=p;
    }
    while(p)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    return 0;
}

第二种:

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};//链表是把结点连接起来,首先建立链表的结点,里面存放数据域和指针域
struct node *creat(int n)
{
    int i;
    struct node *head,*p;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;//申请一个头节点让它为空
    for(i=1; i<=n; i++)
    {
        p=(struct node *)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next=head->next;//要逆序插入链表就要把顺序输入的p结点插在链表最后,我们假设已经有头结点和p,如果再插入一个新的结点,新的结点就要与p连接起来,如果要连接起来那就让新的结点指向p的地址,p的地址由head->next记着,新的p->next=head->next,保存下head的指针域再给他一个新的指针域同时让头结点和新的p连接在一起,就让head->next=新的p
        head->next=p;//建立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;
}
 

第三种:

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};
int main()
{
    struct node *q,*p,*tail;//定义指针
    tail=(struct node *)malloc(sizeof(struct node));
    tail->next=NULL;//建立空链表
    q=tail;
    int n;
    scanf("%d",&n);
    while(n--)//循环建立新结点p,并插入到q后
    {
        p=(struct node *)malloc(sizeof(struct node));//为新结点分配存储空间
        scanf("%d",&p->data);//读入数据
        p->next=q;
        q=p;
    }
    while(q->next)
    {
        printf("%d ",q->data);
        q=q->next;
    }
    printf("\n");
    return 0;
}
发布了183 篇原创文章 · 获赞 5 · 访问量 8845

猜你喜欢

转载自blog.csdn.net/qq_45666654/article/details/104880826
今日推荐