Skip to content

Commit c0cf1f0

Browse files
sum a linked list
1 parent e82195b commit c0cf1f0

File tree

1 file changed

+103
-0
lines changed
  • Python/chapter02/2.5 - Sum Lists

1 file changed

+103
-0
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
#!/usr/bin/python3
2+
3+
import unittest
4+
5+
6+
class Node:
7+
def __init__(self, data, next=None):
8+
self.data = data
9+
self.next = next
10+
11+
12+
class SinglyLinkedList:
13+
def __init__(self):
14+
self.head = None
15+
16+
def addNode(self, data):
17+
node = Node(data)
18+
if not self.head:
19+
self.head = node
20+
else:
21+
temp = self.head
22+
while temp.next:
23+
temp = temp.next
24+
temp.next = node
25+
print("Node added -->", data)
26+
27+
def printList(self):
28+
temp = self.head
29+
while temp:
30+
print(temp.data)
31+
temp = temp.next
32+
33+
def findLength(self, ll):
34+
if not ll.head:
35+
print('No list to traverse')
36+
return
37+
temp = ll.head
38+
count = 0
39+
while temp:
40+
count += 1
41+
temp = temp.next
42+
return count
43+
44+
def turnIntoNum(self, ll, direction=True):
45+
'''if direction = true, then sum in place
46+
if direction = false, then reverse the ll to sum'''
47+
48+
if not ll.head:
49+
print('No list to traverse')
50+
return
51+
num = 0
52+
length = self.findLength(ll)
53+
if direction:
54+
power = length - 1
55+
n = 0
56+
temp = ll.head
57+
while n < length:
58+
if direction:
59+
num += temp.data * (10 ** power)
60+
power -= 1
61+
else:
62+
num += temp.data * (10 ** n)
63+
temp = temp.next
64+
n += 1
65+
print("Number to sum", num)
66+
return num
67+
68+
def addTwoLinkedLists(self, l1, l2, direction=True):
69+
num1 = self.turnIntoNum(l1, direction)
70+
num2 = self.turnIntoNum(l2, direction)
71+
if num1 and num2:
72+
return num1 + num2
73+
else:
74+
print('No numbers to return')
75+
return
76+
77+
78+
class Test(unittest.TestCase):
79+
@classmethod
80+
def setUpClass(cls):
81+
cls.l = SinglyLinkedList()
82+
cls.l.addNode(7)
83+
cls.l.addNode(1)
84+
cls.l.addNode(6)
85+
86+
cls.k = SinglyLinkedList()
87+
cls.k.addNode(5)
88+
cls.k.addNode(9)
89+
cls.k.addNode(2)
90+
91+
@classmethod
92+
def tearDownClass(cls):
93+
pass
94+
95+
def test1(self):
96+
sumReverse = self.l.addTwoLinkedLists(self.l, self.k, False)
97+
print('Sum ->', sumReverse)
98+
sumLL = self.l.addTwoLinkedLists(self.l, self.k)
99+
print('Sum ->', sumLL)
100+
101+
102+
if __name__ == '__main__':
103+
unittest.main()

0 commit comments

Comments
 (0)