Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created July 23, 2019 17:41
Show Gist options
  • Save dgodfrey206/6209d1fc007d13d7309ca387e6298a36 to your computer and use it in GitHub Desktop.
Save dgodfrey206/6209d1fc007d13d7309ca387e6298a36 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <map>
#include<bits/stdc++.h>
using namespace std;
struct Node {
int val;
Node*next=0;
};
Node* nn(int d){
return new Node{d};
}
Node* insert(Node* head, int d) {
if (!head) return nn(d);
Node* t=head;
while (t->next){
t=t->next;
}
t->next=nn(d);
return head;
}
void display(Node*head){
while(head){cout<<head->val<<" ";head=head->next;}
cout<<endl;
}
Node* insertNum(Node* left, Node* right, int num) {
Node* prev = left;
for (auto c : to_string(num)) {
left->val = c-'0';
prev = left;
left = left->next;
}
return prev;
}
Node* sumParts(Node* head) {
if (!head || !head->next) return head;
Node* cur = head;
int sum = 0;
while (cur && cur->val != 0) {
sum += cur->val;
cur = cur->next;
}
if (cur) {
Node* rest = sumParts(cur->next);
cur = insertNum(head, cur, sum);
cur->next = rest;
}
return head;
}
int main(){
Node*head=0;
vector<int>nums={0,1};
for(int i:nums)head=insert(head,i);
display(head);
head = sumParts(head);
display(head);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment