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):
   head = ListNode(elements[0])
   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))

Input

[5,8,1,2,4,7,5]

Output

[2, 5, 15, 10, ]
raja
Published on 19-Nov-2020 11:29:58
Advertisements