2024年2月7日 星期三

[445] Add Two Numbers II

竟然是這題!!!!!!
幸好我還有想到reverse 這件事Orz
但reverse 完卻忘記reverse 回來真是太悲了 Orz
而居然leetcode 上面是要求不要對input linked list 做reverse !
看很多人都提到stack,總覺得這跟reverse沒什麼不一樣啊哈哈哈哈哈XD!
總之那就胡亂用個暴力法解決好了,把數字倒出來到array[100]裡面,讓它們去各字相加,最後存到array3[100]裡面,處理十進位問題,然後再建linked list ! 先降XD!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int *stack1= calloc (100, sizeof(int));//0-99
int *stack2= calloc (100, sizeof(int));
int count1=0, count2=0;
struct ListNode *p1 = l1;
struct ListNode *p2 = l2;

while (p1 != NULL)
{
stack1[count1++]= p1->val;
p1= p1->next;
}
while (p2 != NULL)
{
stack2[count2++]= p2->val;
p2= p2->next;
}

int *stack3= calloc (100, sizeof(int));
int count3=0;
if (count1 >= count2)
{
int i=count1, j=count2;
while (j>0)
{
stack3[count3++]= stack1[--i]+stack2[--j];
}
while (i>0)
stack3[count3++]= stack1[--i];
}
else if (count1 < count2)
{
int i=count1, j=count2;
while (i >0)
{
stack3[count3++]= stack1[--i]+stack2[--j];
}
while (j>0)
stack3[count3++]= stack2[--j];
}

for (int i=0; i<count3; i++)
{
if (stack3[i]>=10)
{
stack3[i]-=10;
if (i+1 == count3)
count3++;
stack3[i+1]++;
}
}
struct ListNode *newHead= NULL;
struct ListNode *ptr;
newHead = calloc(1, sizeof(struct ListNode));
ptr = newHead;
while (count3>0)
{
ptr->val = stack3[--count3];
if (count3 >0)
ptr->next = calloc(1, sizeof(struct ListNode));
ptr = ptr->next;

}
return newHead;
}


沒有留言:

張貼留言