Skip to content

Commit f9323e3

Browse files
authored
Add_one_to_LinkedList
Initial File
1 parent 7b05f91 commit f9323e3

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

Add_one_to_LinkedList

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class Node:
2+
def __init__(self, data):
3+
self.data = data
4+
self.next = None
5+
6+
def newNode(data):
7+
return Node(data)
8+
9+
def reverseList(head):
10+
if not head:
11+
return
12+
curNode = head
13+
prevNode = head
14+
nextNode = head.next
15+
curNode.next = None
16+
17+
while(nextNode):
18+
curNode = nextNode
19+
nextNode = nextNode.next
20+
curNode.next = prevNode
21+
prevNode = curNode
22+
23+
return curNode
24+
25+
26+
def addOne(head):
27+
28+
head = reverseList(head)
29+
k = head
30+
carry = 0
31+
prev = None
32+
head.data += 1
33+
34+
while(head != None) and (head.data > 9 or carry > 0):
35+
prev = head
36+
head.data += carry
37+
carry = head.data // 10
38+
head.data = head.data % 10
39+
head = head.next
40+
41+
if carry > 0:
42+
prev.next = Node(carry)
43+
return reverseList(k)
44+
45+
def printList(head):
46+
if not head:
47+
return
48+
while(head):
49+
print("{}".format(head.data), end="")
50+
head = head.next
51+
52+
if __name__ == '__main__':
53+
head = newNode(1)
54+
head.next = newNode(9)
55+
head.next.next = newNode(9)
56+
head.next.next.next = newNode(9)
57+
58+
print("List is: ", end="")
59+
printList(head)
60+
61+
head = addOne(head)
62+
63+
print("\nResultant list is: ", end="")
64+
printList(head)
65+

0 commit comments

Comments
 (0)