-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist_version.cpp
More file actions
123 lines (117 loc) · 2.47 KB
/
linkedlist_version.cpp
File metadata and controls
123 lines (117 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
//@Anurag Maurya i love recursion
//beautiful use of recusion on linked list <3<3<3
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
node *next;
int len;
node()
{
len=1;
}
node(int x):data(x),len(1),next(0)
{
}
};
node *insert(node *root)//function for inserting in the list
{
node *tem,*nu;
int x;
if(!root)
{
cout<<"enter data"<<"\n";
cin>>x;
nu=new node;
nu->data=x;
nu->next=NULL;
root=nu;
}
else
{
tem=root;
while(tem->next)
tem=tem->next;
cout<<"enter data"<<"\n";
cin>>x;
nu=new node;
nu->data=x;
nu->next=NULL;
nu->len=tem->len+1;
tem->next=nu;
}
return root;
}
int display(node *tem)
{
int c=0;
while(tem)
{
cout<<tem->data<<" ";
tem=tem->next;
c++;
}
cout<<endl;
return c;
}
void fibonacci_array(node *root,int n,node *tem,int l=0)
{
for(int i=l;i<n;i++)//transversing through every possible indexes
{
if(tem->next==NULL)//if we reached last element
{
return;
}
if(tem->data>0&&tem->next->data>0&&tem->next->next)//case 1
{
tem->data--;
tem->next->data--;
tem->next->next->data++;
display(root);
fibonacci_array(root,n,tem,i);
tem->data++;
tem->next->data++;
tem->next->next->data--;
tem=tem->next;
}
else if(tem->data>0&&tem->next->data>0&&tem->next->next==NULL)//case 2
{
tem->data--;
tem->next->data--;
node *nu=new node;
nu->data=1;
nu->next=NULL;
tem->next->next=nu;
display(root);
fibonacci_array(root,n+1,tem,i);
tem->data++;
tem->next->data++;
tem->next->next=NULL;
return;
}
else if(tem->data==0&&tem->next->data>0&&tem->next->next)//for avoiding the case when ith element is 0 while i+1th element is non zero
{
fibonacci_array(root,n,tem->next,i+1);
return;
}
}
}
signed main()
{
node *root=NULL;
char ch;
int x;
do
{
root=insert(root);//creating original array using list
x=display(root);
cout<<"again"<<"\n";
cin>>ch;
}while(ch=='y');
cout<<"\n\n";
x=display(root);//printing the original array
node *tem=root;//pointer that will transverse the list while root will be fixxed
fibonacci_array(root,x,tem);
return 0;
}