主要是确定递归基是n==0 然后有点像中文语言一样,第一个节点是p,然后它的next就是cteateList(n-1)。到此,已经完成所有操作。
#include<iostream>
using namespace std;
struct Node{
int data;
Node *next;
};
Node * createList(int n){
if(n==0)return NULL;
Node*p=new Node;
cin>>p->data;
p->next=createList(n-1);
return p;
}
int main(){
cout<<"递归建立单链表"<<endl;
cout<<"请输入链表元素个数:"<<endl;
int n;
cin>>n;
Node* head=createList(n);
while(head!=NULL){
cout<<head->data<<" ";
head=head->next;
}
return 0;
}