B - 数据结构实验之链表二:逆序建立链表(头插法)

在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int data;
    node *next;
};
int main()
{
    struct node*head;
    head=new node();
    head->next=NULL;
    node *p, *q;
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        p=new node();
        cin>>p->data;
        p->next=head->next;
        head->next=p;
    }
    p=head->next;
    while(p!=NULL)
    {
        if(p->next!=NULL)
            cout<<p->data<<" ";
        else
            cout<<p->data;
        p=p->next;
    }
    return 0;
}

下边代码是将创建过程写成函数

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int data;
    node *next;
};
void creatlist(node *listhead,int n)
{
    node *p;
    for(int i=0;i<n;i++)
    {
        p=new node();
        cin>>p->data;
        p->next=listhead->next;
        listhead->next=p;
    }
}
int main()
{
    struct node*head;
    head=new node();
    head->next=NULL;
    node *p, *q;
    int n;
    cin>>n;
    creatlist(head,n);
    p=head->next;
    while(p!=NULL)
    {
        if(p->next!=NULL)
            cout<<p->data<<" ";
        else
            cout<<p->data;
        p=p->next;
    }
    return 0;
}

发布了65 篇原创文章 · 获赞 2 · 访问量 840

猜你喜欢

转载自blog.csdn.net/weixin_43797452/article/details/104826582
今日推荐