# Program to find folded list from a given linked list in Python

PythonServer Side ProgrammingProgramming

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 −

• temp := 0
• ptr := node
• while ptr is not null, do
• temp := temp + 1
• ptr := next of ptr
• t := quotient of temp / 2
• m := node
• stk := a new stack
• while t is non-zero, do
• push value of m into stk
• tmp := next of m
• next of m := null
• m := tmp
• t := t - 1
• node := m
• if temp is even, then
• m := next of m
• while m is not null, do
• value of m := value of m + stack top element.
• pop from stk
• m := next of m
• return node

Let us see the following implementation to get better understanding −

## Example

Live Demo

class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
for element in elements[1:]:
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
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()
print_list(ob.solve(head))
[5,8,1,2,4,7,5]
[2, 5, 15, 10, ]