Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find folded list from a given linked list in Python
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].
Understanding the Folding Process
The folding process works as follows:
- Split the linked list into two halves
- Reverse the first half using a stack
- Add corresponding nodes from the reversed first half to the second half
- If the list has odd length, skip the middle element
Algorithm Steps
To solve this problem, we follow these steps:
- Count the total number of nodes in the linked list
- Find the middle point and split the list
- Store the first half in a stack (which reverses it)
- If the list length is odd, skip the middle element
- Add values from the stack to the second half nodes
- Return the modified second half as the result
Implementation
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
result = []
while ptr:
result.append(ptr.val)
ptr = ptr.next
print(result)
class Solution:
def solve(self, node):
# Count total nodes
temp = 0
ptr = node
while ptr:
temp += 1
ptr = ptr.next
# Find middle point
t = temp // 2
m = node
stk = []
# Store first half in stack and break the connection
while t:
stk.append(m.val)
tmp = m.next
m.next = None
m = tmp
t -= 1
# Update node to point to second half
node = m
# Skip middle element if odd length
if temp % 2 != 0:
m = m.next
# Add stack values to second half
while m:
m.val += stk.pop()
m = m.next
return node
# Test the solution
ob = Solution()
head = make_list([5, 8, 1, 2, 4, 7, 5])
result = ob.solve(head)
print_list(result)
[2, 5, 15, 10]
How It Works
For the input [5,8,1,2,4,7,5]:
- Total length: 7 nodes
- First half:
[5,8,1]? stored in stack as[1,8,5] - Middle element:
2(skipped because length is odd) - Second half:
[4,7,5] - Final result:
[2, 4+1, 7+8, 5+5]=[2, 5, 15, 10]
Time and Space Complexity
Time Complexity: O(n) where n is the number of nodes, as we traverse the list twice.
Space Complexity: O(n/2) for the stack to store the first half of the list.
Conclusion
This algorithm efficiently folds a linked list by using a stack to reverse the first half and then adding corresponding values. The key insight is properly handling the middle element in odd-length lists.
