forked from geekcomputers/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd_two_Linked_List.py
More file actions
Latest commit
68 lines (58 loc) · 1.85 KB
/
Copy pathAdd_two_Linked_List.py
File metadata and controls
68 lines (58 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
classNode:
def__init__(self, data):
self.data=data
self.next=None
classLinked_List:
def__init__(self):
self.head=None
defInsert_At_Beginning(self, new_data):
new_node=Node(new_data)
ifself.headisNone:
self.head=new_node
return
new_node.next=self.head
self.head=new_node
defAdd_two_no(self, First, Second):
prev=None
temp=None
carry=0
whileFirstisnotNoneorSecondisnotNone:
first_data=0ifFirstisNoneelseFirst.data
second_data=0ifSecondisNoneelseSecond.data
Sum=carry+first_data+second_data
carry=1ifSum>=10else0
Sum=SumifSum<10elseSum%10
temp=Node(Sum)
ifself.headisNone:
self.head=temp
else:
prev.next=temp
prev=temp
ifFirstisnotNone:
First=First.next
ifSecondisnotNone:
Second=Second.next
ifcarry>0:
temp.next=Node(carry)
defDisplay(self):
temp=self.head
whiletemp:
print(temp.data, "->", end=" ")
temp=temp.next
print("None")
if__name__=="__main__":
First=Linked_List()
Second=Linked_List()
First.Insert_At_Beginning(6)
First.Insert_At_Beginning(4)
First.Insert_At_Beginning(9)
Second.Insert_At_Beginning(2)
Second.Insert_At_Beginning(2)
print("First Linked List: ")
First.Display()
print("Second Linked List: ")
Second.Display()
Result=Linked_List()
Result.Add_two_no(First.head, Second.head)
print("Final Result: ")
Result.Display()