题目:
示例:
思路:
有点相似于:链表相加II,这道题我们仍然有进位,但不同的是,链表相加我们选择了开辟新节点,这道题我们选择反转两次链表,开始一次,结束一次。
单链表的翻转详细讲解:反转一个单链表(<---点击可看详解)
题解代码:
struct ListNode* reverse(struct ListNode* head)
{
struct ListNode* n1 = NULL;
struct ListNode* n2 = head;
struct ListNode* n3 = NULL;
if(n2)
n3 = n2->next;
while (n2)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if (n3)
n3 = n3->next;
}
return n1;
}
struct ListNode* doubleIt(struct ListNode* head)
{
struct ListNode* prev = NULL;
struct ListNode* Back = reverse(head);
head = Back;
int add = 0;
while(Back)
{
int temp = Back->val * 2 + add;
add = temp / 10;
prev = Back;
Back->val = temp % 10;
Back = Back->next;
}
if(add > 0)
{
struct ListNode* newnode = malloc(sizeof(struct ListNode));
newnode->val = add;
newnode->next = NULL;
prev->next = newnode;
}
head = reverse(head);
return head;
}
个人主页:Lei宝啊
愿所有美好如期而遇