Suppose we have a linked list. We have to take the first half of the linked list and fold over the second half then merge the intersecting nodes by taking their sum. Finally, we have to return the resulting head of the linked list.
So, if the input is like [5,8,1,2,4,7,5], then the output will be [2, 5, 15, 10, ]
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def print_list(head): ptr = head print('[', end = "") while ptr: print(ptr.val, end = ", ") ptr = ptr.next print(']') class Solution: def solve(self, node): temp = 0 ptr = node while ptr: temp += 1 ptr = ptr.next t = temp // 2 m = node stk =  while t: stk.append(m.val) tmp = m.next m.next = None m = tmp t -= 1 node = m if temp % 2 != 0: m = m.next while m: m.val += stk.pop() m = m.next return node ob = Solution() head = make_list([5,8,1,2,4,7,5]) print_list(ob.solve(head))
[2, 5, 15, 10, ]