Skip to content

Instantly share code, notes, and snippets.

@bitcpf
Created June 28, 2014 14:02
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 bitcpf/b4233e9747980b42fdb5 to your computer and use it in GitHub Desktop.
Save bitcpf/b4233e9747980b42fdb5 to your computer and use it in GitHub Desktop.
/*
Created by bitcpf
*/
public class Addup {
public static Node Addlist(Node head1, Node head2, int up_dig){
int digit_add;
if(head1 == null && up_dig ==0){
return head2;
}
if(head2 == null && up_dig == 0){
return head1;
}
if(head2 == null && head1 == null){
if(up_dig != 0){
digit_add = 0;
}
else{
return null;
}
}
else{
if(head1 == null){
digit_add = head2.getval();
}
else if(head2 == null){
digit_add = head1.getval();
}
else{
digit_add = (head1.getval() + head2.getval());
}
}
Node rs_head = new Node((digit_add+up_dig)%10);
int flag = (digit_add+up_dig)/10;
if(head1 != null || head2 != null || flag!= 0){
if(head1 == null && head2 == null){
rs_head.next = Addlist(null,null,flag);
}
else if(head1 == null){
rs_head.next = Addlist(null,head2.next,flag);
}
else if(head2 == null){
rs_head.next = Addlist(head1.next,null,flag);
}
else{
rs_head.next = Addlist(head1.next,head2.next,flag);
}
}
return rs_head;
}
public static void printlist(Node head){
while(head.next != null){
System.out.print(head.item);
head = head.next;
}
System.out.println(head.item);
}
public static void main(String[] args){
Node f_1 = new Node(7);
Node f_2 = new Node(1);
Node f_3 = new Node(6);
Node f_4 = new Node(9);
f_1.next = f_2;
f_2.next = f_3;
f_3.next = f_4;
Node s_1 = new Node(5);
Node s_2 = new Node(9);
Node s_3 = new Node(3);
s_1.next = s_2;
s_2.next = s_3;
printlist(f_1);
printlist(s_1);
printlist(Addlist(f_1,s_1,0));
}
}
public class Node<Item> {
Item item = null;
Node next = null;
public Node(Item input){
this.item = input;
this.next = null;
}
public int getval(){
return (Integer) (this.item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment