Skip to content

Commit b234483

Browse files
Create sum_of_all_numbers_in_even_positions.c
1 parent 586e205 commit b234483

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
/* Link list node */
5+
struct Node {
6+
int data;
7+
struct Node* next;
8+
};
9+
10+
/* Function to get the alternate
11+
nodes of the linked list */
12+
int sumAlternateNode(struct Node* head)
13+
{
14+
int count = 0;
15+
int sum = 0;
16+
17+
while (head != NULL) {
18+
19+
// when count is even sum the nodes
20+
if (count % 2 == 0)
21+
sum += head->data;
22+
23+
// count the nodes
24+
count++;
25+
26+
// move on the next node.
27+
head = head->next;
28+
}
29+
return sum;
30+
}
31+
32+
// Function to push node at head
33+
void push(struct Node** head_ref, int new_data)
34+
{
35+
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
36+
new_node->data = new_data;
37+
new_node->next = (*head_ref);
38+
(*head_ref) = new_node;
39+
}
40+
41+
// Driver code
42+
int main()
43+
{
44+
/* Start with the empty list */
45+
struct Node* head = NULL;
46+
47+
/* Use push() function to construct
48+
the below list 1 -> 5 -> 2 -> 4 -> 8 -> 6 */
49+
push(&head, 1);
50+
push(&head, 5);
51+
push(&head, 2);
52+
push(&head, 4);
53+
push(&head, 8);
54+
push(&head, 6);
55+
56+
printf("%d", sumAlternateNode(head));
57+
return 0;
58+
}

0 commit comments

Comments
 (0)