-
Notifications
You must be signed in to change notification settings - Fork 0
/
Decimal Equivalent of Binary Linked List.cpp
98 lines (85 loc) · 2.07 KB
/
Decimal Equivalent of Binary Linked List.cpp
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
/* Method - 1
reverse the linked list by recursion
Time complexity - O(N)
Space complexity- O(N) - Recursion stack space
*/
#define ll long long
int mod=1e9+7;
class Solution
{
public:
Node* reverse(Node* root)
{
if(!root)
return NULL;
if(root->next==NULL)
return root;
Node* temp=reverse(root->next);
root->next->next=root;
root->next=NULL;
return temp;
}
int binaryToDecimal(Node* head)
{
int ans=0;
int power=1;
while(head)
{
if(head->data)
ans=(ans+power)%mod;
power=(power*2)%mod;
head=head->next;
}
return ans;
}
long long unsigned int decimalValue(Node *head)
{
Node* rev=reverse(head);
Node* temp=rev;
ll ans=binaryToDecimal(rev);
return ans;
}
};
/* Method - 2
reverse the linked list by Iterative
Time complexity - O(N)
Space complexity- O(1)
*/
#define ll long long
int mod=1e9+7;
class Solution
{
public:
Node* reverse(Node* root)
{
Node* pre=NULL;
while(root)
{
Node* nextRoot=root->next;
root->next=pre;
pre=root;
root=nextRoot;
}
return pre;
}
int binaryToDecimal(Node* head)
{
int ans=0;
int power=1;
while(head)
{
if(head->data)
ans=(ans+power)%mod;
power=(power*2)%mod;
head=head->next;
}
return ans;
}
long long unsigned int decimalValue(Node *head)
{
Node* rev=reverse(head);
Node* temp=rev;
ll ans=binaryToDecimal(rev);
return ans;
}
};