/*****************************************************************
APPLICATION : Addition of Very Long Integers (using Linked List)
CODED BY : Ankit Pokhrel
COMPILED ON : Borland C++ Ver 5.02
DATE : 2010 - July - 02
******************************************************************/
#include "iostream.h"
#include "conio.h"
#include "stdlib.h"
struct List //Structure to represent a node
{
int data;
struct List *next,*head,*Top;
};
typedef List node;
node *New;
void initialize(node **n) //Function to initialize a Node
{
(*n) = new node;
(*n) -> next = NULL;
(*n) -> head = NULL;
(*n) -> Top == NULL;
}
void create(int Item) //Function to create a node
{
New = new node;
New -> next = NULL;
New -> data = Item;
}
void push(node *n,int Item) //Function to add data to stack
{
if(n -> Top == NULL) //if first item
{
n -> data = Item;
n -> head = n;
n -> Top = n;
return;
}
create(Item);
n -> Top -> next = New;
n -> Top = New;
}
int pop(node *n) //Function to delete item from node
{
if(n -> Top == NULL) //if no data
return -999;
node *poped,*temp = n -> head;
if(n -> Top == n -> head)
{
poped = n -> head;
n -> Top = NULL;
n -> head = NULL;
return poped -> data;
}
while(temp -> next != n -> Top) //traverse to second last node
temp = temp -> next;
poped = n -> Top;
temp -> next = NULL;
n -> Top = temp;
return poped -> data;
}
void display(node *n,int carry) //Function to display the items of stack
{
if(n -> Top == NULL) //if no Items
{
cout << "Stack is Empty.";
return;
}
int rev[100],i = 0;
node *temp = n -> head;
rev[i++] = temp -> data; //save data to array
while(temp -> next != NULL)
{
temp = temp -> next;
rev[i++] = temp -> data;
}
if(carry)
cout << carry;
for(int j = i-1;j >= 0;j--) //Display data in reverse order
cout << rev[j];
}
int main()
{
node *opr1,*opr2,*result;
//Initalize all nodes
initialize(&opr1);
initialize(&opr2);
initialize(&result);
char oprand1[100],oprand2[100],ch[2];
//Scan Inputs
cout << "Enter Number : ";
cin >> oprand1;
int i = 0,value,len1,len2,len;
oprand1[i-1] = ' ';
while(oprand1[i] != '\0')
{
ch[0] = oprand1[i];
ch[1] = '\0';
value = atoi(ch);
push(opr1,value);
i++;
}
len1 = i;
cout << "Enter Number : ";
cin >> oprand2;
i = 0;
oprand2[i-1] = ' ';
while(oprand2[i] != '\0')
{
ch[0] = oprand2[i];
ch[1] = '\0';
value = atoi(ch);
push(opr2,value);
i++;
}
len2 = i;
if(len1 > len2)
len = len1;
else
len = len2;
int value1,value2,value3,carry = 0;
while(len > 0) //while data on largest Stack
{
value1 = pop(opr1); //pop data
if(value1 == -999) //if no data
value1 = 0; //set value1 to zero
value2 = pop(opr2); //pop data
if(value2 == -999) //if no data
value2 = 0; //set value2 to zero
value3 = value1 + value2 + carry; //Add all data
carry = value3/10; //Find Carry
if(carry)
value3 -= 10 * carry; //Remove Carry part
push(result,value3); //push result to different stack
len--;
}
cout << "\nResult : ";
display(result,carry); //Display result
getch();
return 0;
}
......................
Labels:
Linked List
No comments:
Post a Comment