【PTA】单链表的创建及遍历(C++)

题目:

在这里插入图片描述
代码:

#include <iostream>
using namespace std;
typedef struct node
{
    
    
    int data;
    struct node *next;
}node;
node*Create(int n){
    
    
    node*p1,*p2=NULL,*head;
    int a;
    head=NULL;
    
    cin>>a;
    for(int i=0;i<n;i++){
    
    
        p1=new node;//每次都重新创建一个新的节点来接输入的数字(node是数据类型)
        p1->data=a;
        if(head==NULL){
    
    //第一次循环必经之路
            head=p2=p1;
        }
        else{
    
    //第二次及以后的循环会经过
            p2->next=p1;
            p2=p1;
        }
        cin>>a;
        }
            if(head!=NULL){
    
    
            p2->next=NULL;
    }
    return(head);
}
void Print(const node*head,int n){
    
    //遍历
    const node*p;
    p=head;
    for(int i=0;i<=n-1;i++){
    
    
        if(p->next!=NULL){
    
    
            cout<<p->data<<" ";
        }
        else{
    
    
            cout<<p->data;
            
        }
        p=p->next;
    }
}
int main(){
    
    
    int n;
    node*head;
    cin>>n;
    head=Create(n);
    Print(head,n);
}

猜你喜欢

转载自blog.csdn.net/qq_51669241/article/details/115052421
今日推荐