-
Notifications
You must be signed in to change notification settings - Fork 0
/
1290 Convert Binary Number in a Linked List to Integer.c
86 lines (72 loc) · 1.34 KB
/
1290 Convert Binary Number in a Linked List to Integer.c
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#define MAX_ELEMENTS 30
typedef struct stack
{
int arr[MAX_ELEMENTS];
int top;
}Stack;
int isStackFull(Stack * binary_stack)
{
if(binary_stack->top == MAX_ELEMENTS-1)
{
return 1;
}
else
{
return 0;
}
}
int isStackEmpty(Stack * binary_stack)
{
if(binary_stack->top == -1)
{
return 1;
}
else
{
return 0;
}
}
void enqueue(Stack * binary_stack, int element)
{
if(isStackFull(binary_stack))
{
return;
}
binary_stack->arr[++(binary_stack->top)] = element;
return;
}
int dequeue(Stack * binary_stack)
{
if(isStackEmpty(binary_stack))
{
return 0;
}
int ret_val = binary_stack->arr[(binary_stack->top)--];
return ret_val;
}
int getDecimalValue(struct ListNode* head)
{
Stack binary_stack;
binary_stack.top = -1;
struct ListNode * trav_ptr = head;
while(trav_ptr!=NULL)
{
enqueue(&binary_stack, trav_ptr->val);
trav_ptr = trav_ptr->next;
}
int exp_val = 0;
int num = 0;
while(!isStackEmpty(&binary_stack))
{
num += (dequeue(&binary_stack) * pow(2, exp_val));
exp_val++;
}
return num;
}