Sum the linked lists

Sum the linked lists
1->2->3
4->5

result is 1->6->8

 

1->5->9

5->3

result  2->1->2

A: 把链表的值加起来,注意,根据sample,是从链表的最后一位开始相加,而且,要考虑进位的问题

 

pseudo code如下 (通过编译,但没有测试用例)

View Code
LinkNode* SumLinkLists(LinkNode *p1, LinkNode *p2)
{
if (NULL == p1 && NULL == p2)
return NULL;

if (NULL == p1 && NULL != p2)
return p2;

if (NULL != p1 && NULL == p2)
return p1;

std::stack<LinkNode*> s1;
std::stack<LinkNode*> s2;

LinkNode* t1 = p1;
LinkNode* t2 = p2;

while (t1)
{
s1.push(t1);
t1 = t1->next;
}

while (t2)
{
s2.push(t2);
t2 = t2->next;
}

int sum = 0, carry = 0;
LinkNode* p = new LinkNode();
LinkNode* h = p;

while (!s1.empty() && !s2.empty())
{
t1 = s1.top();
t2 = s2.top();

sum = t1->data + t2->data + carry; // 得到当前结点的和,同时加上进位

if (sum > 10) // 计算需要存储到结点上的'和'及'进位'
{
sum = sum%10;
carry = sum/10;
}

LinkNode* n = new LinkNode();
n->data = sum;

p->next = n;
p = p->next;

s1.pop();
s2.pop();
}

// 将剩余的数据也添加进去
std::stack<LinkNode*> &refL = (!s1.empty())? s1:s2;
while (!refL.empty())
{
sum = refL.top()->data + carry;
if (sum > 10)
{
sum = sum%10;
carry = sum/10;
}

LinkNode* n = new LinkNode();
n->data = sum;
p->next = n;
p = p->next;
refL.pop();
}

p = h->next; // 得到真正的head
delete h;
h = NULL;

// reverse the link list p
// 反转链表
LinkNode* pre = p;
p = p->next;
pre->next = NULL;

while (p)
{
// pre -> p -> nex
LinkNode* n = p->next;

p->next = pre;
pre = p;
p = n;
}

return pre;
}



posted @ 2012-01-06 11:12  百分百好牛  阅读(161)  评论(0编辑  收藏  举报