递归建立链表单一head变量

来源:互联网 发布:centos 6 ssh拒绝访问 编辑:程序博客网 时间:2024/06/03 19:01

不得不说今天左右脑同少的感觉真好。

想到自己上次写的那个递归操作,不得不说,又臭又长(还占内存!)点击打开链接

首先来写伪代码:

按照递归的基础思路来写算法。

判断是否要跳出函数

n为0的时候要跳出

然后当这个指针位是否为空,如果为空,说明当前位置存在,切已输入有效值

转入下一位

当为空的时候,说明,到达链表的尾部,生成并输入;

好了,思路如此,上代码。

////  main.cpp//  递归的链表操作////  Created by MaLker on 27/04/2017.//  Copyright © 2017 MaLker. All rights reserved.//#include <iostream>using namespace std;struct Node {    int data;    Node *next;};//用递归建立数组void Creat_List(Node *&head,int n){    if(n==0){//输入满足情况的时候        return ;    }    if(head){//当前指针区域已创造过,且有值        Creat_List(head->next,--n);    }    else{//到达尾部,且能插入时插入相应数值        head=new Node;        cin>>head->data;        Creat_List(head->next,--n);    }}void Show_List(Node *&head){    if(head){//这个类似于树的先序遍历        cout<<head->data<<endl;        //↑↓这是交换之后为后序遍历原理        Show_List(head->next);    }    else{        return ;    }}int main(){    Node *head=NULL;    int n;    cin>>n;    Creat_List(head,n);    Show_List(head);    return 0;}

0 1