Skip to content

Instantly share code, notes, and snippets.

@humbroll
Created August 28, 2016 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humbroll/a422df2563e91fd4ab9b32fcb8c9ae92 to your computer and use it in GitHub Desktop.
Save humbroll/a422df2563e91fd4ab9b32fcb8c9ae92 to your computer and use it in GitHub Desktop.
linked list sum lists
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Question.
# You have two numbers represented by a linked list, where each node contains a single
# digit. The digigts are stored in reverse order, such that the 1's digit is at the head of the list.
# Write a function that adds the two numbers and returns the sum as a linked list.
# Example
# Input: (7 -> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295
# Output: 2 -> 1 -> 9. That is, 912.
# Follow Up
# Suppose the digits are stored in forward order. Repeat the above problem.
# Example
# Input: (6 -> 1 -> 7) + (2 -> 9 -> 5). That is, 617+295
# Output: 9 -> 1 -> 2. That is, 912
class Node:
def __init__(self, value, next=None):
self.value = value
self.next_ptr = next
def __str__(self):
return "%d" % (self.value)
class LinkedList:
def __init__(self):
self.edge_node = None
self.head_node = None
def add_node(self, node):
if not self.edge_node:
self.head_node = node
node.next_ptr = self.edge_node
self.edge_node = node
def add_node_to_head(self, node):
if self.head_node:
self.head_node.next_ptr = node
if not self.edge_node:
self.edge_node = node
self.head_node = node
def add(self, node_value):
new_node = Node(node_value, self.edge_node)
self.add_node(new_node)
return new_node
def add_to_head(self, node_value):
new_node = Node(node_value)
self.add_node_to_head(new_node)
def __add__(self, ll):
result_ll = LinkedList()
cur_n_1, cur_n_2 = self.edge_node, ll.edge_node
cur_sum = cur_n_1.value + cur_n_2.value
while cur_sum > 0:
modulus = cur_sum % 10
result_ll.add_to_head(modulus)
cur_n_1 = cur_n_1.next_ptr if (cur_n_1 and cur_n_1.next_ptr) else None
cur_n_2 = cur_n_2.next_ptr if (cur_n_2 and cur_n_2.next_ptr) else None
cur_sum = cur_sum / 10 # quotient
cur_sum += cur_n_1.value if cur_n_1 else 0
cur_sum += cur_n_2.value if cur_n_2 else 0
return result_ll
def __str__(self):
node_value_arr = []
node = self.edge_node
while node:
node_value_arr.append(str(node))
node = node.next_ptr
return " -> ".join(node_value_arr)
if __name__ == '__main__':
# Setup linkedlist
linked_list_1 = LinkedList()
# linked_list_1.add(9)
linked_list_1.add(6)
linked_list_1.add(1)
linked_list_1.add(7)
linked_list_2 = LinkedList()
linked_list_2.add(2)
linked_list_2.add(9)
linked_list_2.add(5)
print "(%s) + (%s) = (%s)" % (linked_list_1, linked_list_2, (linked_list_1 + linked_list_2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment