#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct Lnode{
int data;
Lnode *next;
};
void reprint(Lnode *L)
{
if(L!=NULL){
reprint(L->next);
cout<<L->data<<'\t';
}
}
int main(){
Lnode *head,*q,*p,*r;
p=(Lnode *)malloc(sizeof(Lnode));
head = p;
p->data = 3;
q=(Lnode *)malloc(sizeof(Lnode));
q->data = 4;
r==(Lnode *)malloc(sizeof(Lnode));
r->data = 5;
r->next = NULL;
q->next = r;
p->next = q;
reprint(head);
}
编译通过 执行失败
不知道为啥
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct Lnode{
int data;
Lnode *next;
};
void reprint(Lnode *L)
{
if(L!=NULL){
reprint(L->next);
cout<<L->data<<'\t';
}
}
void createLinkListR(Lnode *&head){
head = (Lnode *)malloc(sizeof(Lnode));
head->next = NULL;
Lnode *p = NULL,*r = head;
int n;
cin>>n;
for(int i=0;i<n;i++){
p = (Lnode *)malloc(sizeof(Lnode));
p->next = NULL;
cin>>p->data;
p->next = r->next;
r->next = p;
r = p;
}
}
int main(){
Lnode *head;
createLinkListR(head);
reprint(head);
}
结果
5(输入)
1 2 3 4 5(输入)
5 4 3 2 1 1710608(输出)
就假设reprint是可以逆序打印链表
reprint(L->next);
把链表分为两部分
一部分是开始结点 一部分是剩余结点
时间复杂度是O(n)(打印了n个结点)
空间复杂度是O(n)(递归函数展开 需要保护现场有n处 系统占的深处是n)
网友评论