1 Star 0 Fork 0

Shaco_Ma/leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
2_two_link_add 2.67 KB
一键复制 编辑 原始数据 按行查看 历史
Shaco_Ma 提交于 2019-06-25 09:12 . 更新 2_two_link_add
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
1,get the link long and which
2,sum whit bits and copy to longer link
*/
//if ==, return l1
void get_bigger(struct ListNode *l1, struct ListNode *l2,
struct ListNode **bigger, struct ListNode **less)
{
struct ListNode *temp_link;
*bigger = l1;
*less = l2;
int l1_len = 0, l2_len = 0;
while(l1 != NULL || l2 != NULL)
{
if(l1 != NULL)
{
l1_len++;
l1 = l1->next;
}
if(l2 != NULL)
{
l2_len++;
l2 = l2->next;
}
if(l1_len < l2_len && ((l1==NULL&&l2!=NULL)||(l1!=NULL&&l2==NULL)))
{
temp_link = *less;
*less = *bigger;
*bigger = temp_link;
return;
}
}
/*while(l2 != NULL)
{
l2_len++;
l2 = l2->next;
}*/
if(l1_len < l2_len)
{
temp_link = *less;
*less = *bigger;
*bigger = temp_link;
}
}
/*struct ListNode* get_less(struct ListNode *l1, struct ListNode *l2)
{
int l1_len = 0, l2_len = 0;
while(l1 != NULL)
{
l1_len++;
l1 = l1->next;
}
while(l2 != NULL)
{
l2_len++;
l2 = l2->next;
}
if(l1_len >= l2_len)
return l2;
return l1;
}*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode *bigger = NULL, *less = NULL, *ret = NULL, *new = NULL;
struct ListNode *temp = NULL, *last = NULL;
//bigger = get_bigger(l1, l2, &bigger);
//less = get_less(l1, l2, &less);
get_bigger(l1, l2, &bigger, &less);
while(bigger != NULL)
{
if(less != NULL)
{
bigger->val += less->val;
less = less->next;
}
if(bigger->val >= 10)
{
bigger->val -= 10;
if(bigger->next != NULL)
bigger->next->val++;
else
{
new = malloc(sizeof(struct ListNode));
new->next = NULL;
new->val = 1;
bigger->next = new;
}
}
printf("new bigger->val = %d\n", bigger->val);
new = malloc(sizeof(struct ListNode));
new->next = NULL;
new->val = bigger->val;
if(ret == NULL)
{
ret = new;
last = ret;
}
else
{
last->next = new;
last = new;
}
bigger = bigger->next;
}
return ret;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/shaco_ma/leetcode_all.git
git@gitee.com:shaco_ma/leetcode_all.git
shaco_ma
leetcode_all
leetcode
master

搜索帮助