File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments