Skip to content

Instantly share code, notes, and snippets.

@Indy9000
Created October 17, 2019 14:05
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 Indy9000/b6effd08e1dc5704c276cc25aef04390 to your computer and use it in GitHub Desktop.
Save Indy9000/b6effd08e1dc5704c276cc25aef04390 to your computer and use it in GitHub Desktop.
Given a linked list of integers, remove all consecutive nodes that sum up to n.
class Node():
def __init__(self, value, next=None):
self.value = value
self.next = next
# returns a node if the sum is n
def sumTo(n, node):
s = 0
while node != None:
s = s + node.value
if s == n:
return node #found
node = node.next
return None # not found
def removeConsecutiveSumToN(n, node):
prev = None
while node != None:
nn = sumTo(0, node)
if nn!= None: #found
if prev != None:
prev.next = nn.next
else:
prev = nn.next
node = nn.next
else:
prev = node
node = node.next
return prev
def printNode(node):
while node:
print(node.value)
node = node.next
def test1():
print("test1")
node = Node(10)
node = removeConsecutiveSumToN(0, node)
printNode(node)
def test2():
print("test2")
node = Node(10)
node.next = Node(-10)
node = removeConsecutiveSumToN(0, node)
printNode(node)
def test3():
print("test3")
node = Node(10)
node.next = Node(-10)
node.next.next = Node(2)
node = removeConsecutiveSumToN(0, node)
printNode(node)
def test4():
print("test4")
node = Node(10)
node.next = Node(5)
node.next.next = Node(-3)
node.next.next.next = Node(-3)
node.next.next.next.next = Node(1)
node.next.next.next.next.next = Node(4)
node.next.next.next.next.next.next = Node(-4)
node = removeConsecutiveSumToN(0, node)
printNode(node)
def main():
test1()
test2()
test3()
test4()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment