Skip to content

Instantly share code, notes, and snippets.

@detunized
Created October 23, 2012 11:53
Show Gist options
  • Save detunized/3938368 to your computer and use it in GitHub Desktop.
Save detunized/3938368 to your computer and use it in GitHub Desktop.
// A solution for http://www.geeksforgeeks.org/archives/25739
//
// Given two numbers represented by two linked lists, write a function that
// returns sum list. The sum list is linked list representation of addition of
// two input numbers. It is not allowed to modify the lists. Also, not allowed
// to use explicit extra space (Hint: Use Recursion).
//
// Example:
//
// Input:
// First List: 5->6->3 // represents number 563
// Second List: 8->4->2 // represents number 842
// Output:
// Resultant list: 1->4->0->5 // represents number 1405
//
// This solution is very simple, it only works on short lists which represent
// numbers that fit into an int. The bulletproof solution will come later.
#include <memory>
#include <iostream>
struct Node
{
typedef std::auto_ptr<Node> Ptr;
static Ptr create(int digit, Ptr next = Ptr(0))
{
return Ptr(new Node(digit, next));
}
int digit;
Ptr next;
private:
Node(int digit, Ptr next = 0): digit(digit), next(next)
{
}
};
int join(Node::Ptr const &head, int accumulator = 0)
{
if (!head.get())
return accumulator;
return join(head->next, accumulator * 10 + head->digit);
}
Node::Ptr split(int number, Node::Ptr head = Node::Ptr(0))
{
if (!number)
return head;
return split(number / 10, Node::create(number % 10, head));
}
Node::Ptr sum(Node::Ptr const &a, Node::Ptr const &b)
{
return split(join(a) + join(b));
}
std::ostream &operator <<(std::ostream &stream, Node::Ptr const &head)
{
if (!head.get())
stream << "[end]";
else
stream << head->digit << ", " << head->next;
return stream;
}
int main(int argc, char const *argv[])
{
Node::Ptr a = split(563);
Node::Ptr b = split(842);
std::cout << sum(a, b) << std::endl;
return 0;
}
#!/usr/bin/env ruby
# A solution for http://www.geeksforgeeks.org/archives/25739
#
# Given two numbers represented by two linked lists, write a function that
# returns sum list. The sum list is linked list representation of addition of
# two input numbers. It is not allowed to modify the lists. Also, not allowed
# to use explicit extra space (Hint: Use Recursion).
#
# Example:
#
# Input:
# First List: 5->6->3 // represents number 563
# Second List: 8->4->2 // represents number 842
# Output
# Resultant list: 1->4->0->5 // represents number 1405
def join list, accumulator = 0
list ? join(list[:next], accumulator * 10 + list[:digit]) : accumulator
end
def split number, head = nil
number == 0 ? head : split(number / 10, {:digit => number % 10, :next => head})
end
a = split 563
b = split 842
p split join(a) + join(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment