欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

链表-简单练习题2-数据结构实验之链表二:逆序建立链表

程序员文章站 2022-08-02 11:19:53
数据结构实验之链表二:逆序建立链表 Time Limit: 1000 ms Memory Limit: 65536 KiB Submit Statistic Discuss Problem Description 输入整数个数N,再输入N个整数,按照这些整数输入的相反顺序建立单链表,并依次遍历输出单 ......

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

time limit: 1000 ms memory limit: 65536 kib

problem description

输入整数个数n,再输入n个整数,按照这些整数输入的相反顺序建立单链表,并依次遍历输出单链表的数据。

input

第一行输入整数n;;
第二行依次输入n个整数,逆序建立单链表。

output

依次输出单链表所存放的数据。

sample input

10
11 3 5 27 9 12 43 16 84 22 

sample output

22 84 16 43 12 9 27 5 3 11 

hint

不能使用数组!

 

 

代码如下:

#include<iostream>
#include<cstdlib>
using namespace std;
struct int{
    int num;
    struct int *pnxet;
};

int main(){
    int n;
    int* head=(int*)malloc(sizeof(int));
    head->pnxet=null;//建立链表头结点
    
    cin>>n;
    for(int i=0;i<n;i++){
        int* pnew=(int*)malloc(sizeof(int));
        cin>>pnew->num;
        pnew->pnxet =head->pnxet;
        head->pnxet=pnew;
    } 
    //遍历
     int* p=head->pnxet;
     while(p!=null){
         cout<<p->num<<" ";
         p=p->pnxet;
     }
     cout<<endl;
    
}