题解 | #链表相加(二)#
链表相加(二)
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
//反转链表函数
#include<stdlib.h>
struct ListNode* ReverseList(struct ListNode* pHead ) {
if(pHead == NULL) return NULL;
if(pHead->next == NULL) return pHead;
struct ListNode *p1,*p2,*p;
p1 = pHead;
p2 = p1->next;
p1->next = NULL;
while(p2->next != NULL)
{
p = p2->next;
p2->next = p1;
p1 = p2;
p2 = p;
}
p2->next = p1;
pHead = p2;
return pHead;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
// write code here
struct ListNode *p1,*p2;
p1 = ReverseList(head1);
p2 = ReverseList(head2);
struct ListNode *pp1 = p1,*pp2 = p2,*newhead;
while(pp1 != NULL && pp2 != NULL)
{
pp1->val = pp2->val = pp1->val + pp2->val;
pp1 = pp1->next;
pp2 = pp2->next;
}
if(pp1 == NULL) newhead = p2;
else newhead = p1;
p1 = newhead;
while(p1 != NULL)
{
if(p1->next == NULL&&p1->val>=10)
{
p1->next = (struct ListNode *)malloc(sizeof(struct ListNode));
p1->next->next =NULL;
}
if(p1->val>=10)
{
p1->next->val++;
p1->val = p1->val%10;
}
p1 = p1->next;
}
return ReverseList(newhead);
}
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
//反转链表函数
#include<stdlib.h>
struct ListNode* ReverseList(struct ListNode* pHead ) {
if(pHead == NULL) return NULL;
if(pHead->next == NULL) return pHead;
struct ListNode *p1,*p2,*p;
p1 = pHead;
p2 = p1->next;
p1->next = NULL;
while(p2->next != NULL)
{
p = p2->next;
p2->next = p1;
p1 = p2;
p2 = p;
}
p2->next = p1;
pHead = p2;
return pHead;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
// write code here
struct ListNode *p1,*p2;
p1 = ReverseList(head1);
p2 = ReverseList(head2);
struct ListNode *pp1 = p1,*pp2 = p2,*newhead;
while(pp1 != NULL && pp2 != NULL)
{
pp1->val = pp2->val = pp1->val + pp2->val;
pp1 = pp1->next;
pp2 = pp2->next;
}
if(pp1 == NULL) newhead = p2;
else newhead = p1;
p1 = newhead;
while(p1 != NULL)
{
if(p1->next == NULL&&p1->val>=10)
{
p1->next = (struct ListNode *)malloc(sizeof(struct ListNode));
p1->next->next =NULL;
}
if(p1->val>=10)
{
p1->next->val++;
p1->val = p1->val%10;
}
p1 = p1->next;
}
return ReverseList(newhead);
}