class Node{
public int data;
public Node next;
public Node(int n){
this.data = n;
this.next = null;
}
}
public class LinkList{
public Node addNode(Node head, int n){
if(head == null){
head = new Node(n);
return head;
}
Node curr = head;
while(curr.next != null){
curr = curr.next;
}
curr.next= new Node(n);
return head;
}
public static void printLinkList(Node head){
if(head == null){
return;
}
Node curr = head;
while(curr != null){
System.out.print("->"+curr.data);
curr = curr.next;
}
System.out.print("->null");
System.out.println();
}
public static Node addLists(Node head1, Node head2){
if(head1==null && head2==null){
return null;
}else if(head1 == null){
return head2;
}else if(head2 == null){
return head1;
}
Node newHead = null;
Node newCurr = null;
Node curr1 = head1;
Node curr2 = head2;
int carry = 0;
while(curr1 != null && curr2 != null){
int newSum = curr1.data + curr2.data + carry;
if(newSum >= 10){
carry = 1;
newSum = newSum - 10;
}else{
carry = 0;
}
if(newHead == null){//first node
newHead = new Node(newSum);
newCurr = newHead;
}else{//subsequent nodes
newCurr.next = new Node(newSum);
newCurr = newCurr.next;
}
curr1= curr1.next;
curr2= curr2.next;
}
while(curr1 != null){
int newSum = curr1.data + carry;
if(newSum >= 10){
carry = 1;
newSum = newSum - 10;
}else{
carry = 0;
}
newCurr.next = new Node(newSum);
newCurr = newCurr.next;
curr1= curr1.next;
}
while(curr2 != null){
int newSum = curr2.data + carry;
if(newSum >= 10){
carry = 1;
newSum = newSum - 10;
}else{
carry = 0;
}
newCurr.next = new Node(newSum);
newCurr = newCurr.next;
curr2= curr2.next;
}
if(carry == 1){
newCurr.next = new Node(1);
newCurr = newCurr.next;
}
newCurr.next = null;
return newHead;
}
public static void main(String args[]){
LinkList l1 = new LinkList();
Node head1 = l1.addNode(null, 1);
head1 = l1.addNode(head1, 2);
head1 = l1.addNode(head1, 6);
head1 = l1.addNode(head1, 9);
LinkList l2 = new LinkList();
Node head2 = l2.addNode(null, 4);
head2 = l2.addNode(head2, 5);
head2 = l2.addNode(head2, 5);
LinkList.printLinkList(head1);
LinkList.printLinkList(head2);
Node head3 = LinkList.addLists(head1, head2);
LinkList.printLinkList(head3);
}
}
Sunday, March 4, 2012
Add digits stored in linklist nodes.The digits are in reverse order
Eg: Add 354 and 445
L1 : ->4->5->3->null
L2 : ->5->4->4->null
Ans : ->9->9->7->null
Subscribe to:
Posts (Atom)