单向链表>创建节点

#include <stdio.h>
#include <iostream>
#include <stdlib.h>

using namespace std;

struct Person{
    int age;
    struct Person *next;
};
Person *CrtTailNode(){
    Person *head ,*tmp;
    head = tmp = NULL;
    int n;
    cout<<"Node Number:"<<endl;
    cin>>n;
    for(int i = 0;i<n;i++){
    
        tmp = new Person;//(Person*)(malloc(sizeof(Person)));
        cout<<"Age:" <<endl;
        cin >>tmp->age;
        tmp->next = head;
        head  = tmp ;
    
    }
    return head;


}

Person *CrtHeadNode(){
    Person *head,*tail,*tmp;
    int n;
    cout<<"Node Number:"<<endl;
    cin>>n;
    head = tail = tmp = NULL;
    for(int i = 0;i<n;i++){
        tmp = new Person;//(Person*)(malloc(sizeof(Person)));
        cout<<"Age:" <<endl;
        cin >>tmp->age;
        if(head){
            while(tail->next!=NULL){
                tail = tail->next;
            }
            tail->next = tmp;
        }else{
            head = tail = tmp;
        }
    
    }
    return head;


}
void show(Person *head){
    while(head !=NULL){
        cout<<head->age<<endl;
        head = head->next;
    }
}
int main(){
    Person *p;
//    p = CrtHeadNode();
    p = CrtTailNode();
    show(p);
    return 0;

}

原文地址:https://www.cnblogs.com/zhangsf/p/2749131.html