Given a linked list, the task is to find the sum of all the nodes which are greater than the node next to them. Note that for the last node of the linked list which doesn’t have any node next to it, it must be greater than the first node in order for it to contribute to the sum.
Input: 9 -> 2 -> 3 -> 5 -> 4 -> 6 -> 8
9 + 5 = 14
Input: 2 -> 1 -> 5 -> 7
2 + 7 = 9
Approach: Traverse the whole linked list and for each node, if the node is greater than the next node then add it to the sum. For the last node, compare it to the head of the linked list, if last node is greater than the head then add it to the sum. Print the sum in the end.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Create new linked list from two given linked list with greater element at each node
- Delete all the nodes from the doubly linked list that are greater than a given value
- Delete linked list nodes which have a greater value on left side
- Update adjacent nodes if the current node is zero in a Singly Linked List
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Delete N nodes after M nodes of a linked list
- Delete all the nodes from the list that are greater than x
- Swap Kth node from beginning with Kth node from end in a Doubly Linked List
- Next greater element in the Linked List
- Swap Kth node from beginning with Kth node from end in a Linked List
- Linked List Sum of Nodes Between 0s
- Sum of the nodes of a Singly Linked List
- Sum of the alternate nodes of linked list
- Find the sum of last n nodes of the given Linked List
- Sum of all distinct nodes in a linked list
- Find sum of even and odd nodes in a linked list
- Linked List Product of Nodes Between 0s
- Segregate even and odd nodes in a Linked List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.