forked from iamshubhamg/Leet-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add1.py
88 lines (63 loc) · 1.47 KB
/
Add1.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Python3 program to add 1 to a linked list
import sys
import math
# Linked list node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to create a new node with given data */
def newNode(data):
return Node(data)
# Function to reverse the linked list */
def reverseList(head):
if not head:
return
curNode = head
prevNode = head
nextNode = head.next
curNode.next = None
while(nextNode):
curNode = nextNode
nextNode = nextNode.next
curNode.next = prevNode
prevNode = curNode
return curNode
# Adds one to a linked lists and return the head
# node of resultant list
def addOne(head):
# Reverse linked list and add one to head
head = reverseList(head)
k = head
carry = 0
prev = None
head.data += 1
# update carry for next calculation
while(head != None) and (head.data > 9 or carry > 0):
prev = head
head.data += carry
carry = head.data // 10
head.data = head.data % 10
head = head.next
if carry > 0:
prev.next = Node(carry)
# Reverse the modified list
return reverseList(k)
# A utility function to print a linked list
def printList(head):
if not head:
return
while(head):
print("{}".format(head.data), end="")
head = head.next
# Driver code
if __name__ == '__main__':
head = newNode(1)
head.next = newNode(9)
head.next.next = newNode(9)
head.next.next.next = newNode(9)
print("List is: ", end="")
printList(head)
head = addOne(head)
print("\nResultant list is: ", end="")
printList(head)