您的位置:首页 > 其它

Cracking The Coding Interview2.4

2014-04-09 13:31 330 查看
删除前面的linklist,使用node来表示链表
//	You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
//
//	EXAMPLE
//
//Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
//
//Output: 8 -> 0 -> 8

#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};

void init(node *p,int a[], int size)
{
if (a==NULL || size<0)
{
return;
}

for (int i = 0; i < size; i++)
{
node *t = new node;
t->data = a[i];
p->next = t;
p = p->next;
}
p->next = NULL;
}

void print(node *head)
{
if (!head)
{
return;
}

node *p = head->next;

while (p)
{
cout<<p->data<<"  ";
p = p->next;
}
cout<<endl;
}

node * plus(node *a, node *b)
{
node *pa = a->next;
node *pb = b->next;
node *pc = new node;
node *pi = pc;
int i = 0;
int step = 0;
while(pa!=NULL && pb!= NULL)
{
node *t = new node;

int temp = pa->data + pb->data +step;
step = 0;
if (temp >=10)
{
temp %= 10;
step = 1;
}

t->data =temp;
pi->next = t;
pi = t;
pa = pa->next;
pb = pb->next;

}

while(pa!= NULL)
{
node *t = new node;
t->data = pa->data + step;
step = 0;
pi->next = t;
pi = t;
pa = pa->next;
}

while(pb != NULL)
{
node *t = new node;
t->data = pb->data + step;
step = 0;
pi->next = t;
pi = t;
pb = pa->next;
}

if (step>0)
{
node *t = new node;
t->data = step;
pi->next = t;
pi = t;
}
pi->next = NULL;

return pc;

}

int main()
{
int a[6] = {1,4,5,9,7,8};
node *head = new node;
init(head,a,6);
print(head);

int b[6] = {1,4,5,9,7,8};
node *h = new node;
init(h,a,6);
print(h);

node * r = plus(head, h);
print(r);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: