Skip to content

Instantly share code, notes, and snippets.

@ishankhare07
Last active September 30, 2015 13:45
Show Gist options
  • Save ishankhare07/2fdfbbd57cc393bf18ea to your computer and use it in GitHub Desktop.
Save ishankhare07/2fdfbbd57cc393bf18ea to your computer and use it in GitHub Desktop.
linked numbers
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int value) {
data = value;
next = NULL;
}
};
class Stack {
Node *arr[100];
Node **top;
public:
Stack() {
top = arr;
}
void push(Node *node) {
*top++ = node;
}
void print() {
Node **temp = top;
while(temp-- >= arr) {
cout<<(*temp)->data<<"->";
}
}
};
Node* convertToLL(int a) {
Node *start = NULL, *current = NULL;
if (a > 0) {
while(a) {
if (start == NULL) {
start = new Node(a % 10);
current = start;
} else {
Node *temp = new Node(a % 10);
current->next = temp; // 123 -> 3 -> 2 -> 1
current = current->next;
}
a /= 10;
}
} else {
start = new Node(0);
}
return start;
}
Stack result(Node* first, Node *second) {
int carry=0;
Node *start = NULL, *current, *temp;
Stack s;
while(first != NULL && second != NULL) {
if (first == NULL) {
temp = new Node(second->data + carry);
second = second->next;
} else if (second == NULL) {
temp = new Node(first->data + carry);
first = first->next;
} else {
temp = new Node(first->data + second->data + carry);
first = first->next;
second = second->next;
}
if (temp->data > 9) {
carry = temp->data / 10;
temp->data = temp->data % 10;
}
s.push(temp);
}
return s;
}
int main() {
int a, b;
cout<< "Enter 2 numbers: ";
cin>>a>>b;
Node *first = convertToLL(a);
Node *second = convertToLL(b);
Stack answer = result(first, second);
answer.print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment