Given a singly linked list containing n nodes. Modify the value of first half nodes such that 1st node’s new value is equal to the last node’s value minus first node’s current value, 2nd node’s new value is equal to the second last node’s value minus 2nd node’s current value, likewise for first half nodes. If n is odd then the value of the middle node remains unchanged.
Input: 10 -> 4 -> 5 -> 3 -> 6
Output: -4 -> -1 -> 5 -> 3 -> 6
Input: 2 -> 9 -> 8 -> 12 -> 7 -> 10
Output: 8 -> -2 -> 4 -> 12 -> 7 -> 10
Approach: Traverse the link list using recursion for only second half of the list rather than recursing the whole list, thereby reducing the stack frame. Based on the number of nodes in the list, we calculate the starting point for the second half of the list and the list is recursed for the second half. Once the second half is recursed completely, the value of the node present in the stack and the value of the current node is subtracted.
Below is the implementation of the above approach:
8 -> -2 -> 4 -> 12 -> 7 -> 10
- Modify contents of Linked List
- Recursive Approach to find nth node from the end in the linked list
- Recursive approach for alternating split of Linked List
- Print the last k nodes of the linked list in reverse order | Recursive approach
- How to write C functions that modify head pointer of a Linked List?
- A Programmer's approach of looking at Array vs. Linked List
- Construct a linked list from 2D matrix (Iterative Approach)
- Recursive insertion and traversal linked list
- Reverse a Linked List in groups of given size (Iterative Approach)
- Check if linked list is sorted (Iterative and Recursive)
- Recursive function to delete k-th node from linked list
- Find Length of a Linked List (Iterative and Recursive)
- Search an element in a Linked List (Iterative and Recursive)
- Iterative approach for removing middle points in a linked list of line segements
- Recursive selection sort for singly linked list | Swapping node links
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.
Improved By : kanimozhi_mb