-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum_of_all_numbers_in_even_positions.c
58 lines (48 loc) · 1.15 KB
/
sum_of_all_numbers_in_even_positions.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
#include <stdio.h>
#include <stdlib.h>
/* Link list node */
struct Node {
int data;
struct Node* next;
};
/* Function to get the alternate
nodes of the linked list */
int sumAlternateNode(struct Node* head)
{
int count = 0;
int sum = 0;
while (head != NULL) {
// when count is even sum the nodes
if (count % 2 == 0)
sum += head->data;
// count the nodes
count++;
// move on the next node.
head = head->next;
}
return sum;
}
// Function to push node at head
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
// Driver code
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Use push() function to construct
the below list 1 -> 5 -> 2 -> 4 -> 8 -> 6 */
push(&head, 1);
push(&head, 5);
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 6);
printf("%d", sumAlternateNode(head));
return 0;
}