LeetCode-2-Add Two Nuns(C语言实现)
来源:互联网 发布:js touchevent事件 编辑:程序博客网 时间:2024/06/03 22:22
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(structListNode* l1, structListNode* l2) {
int add = 0; //记录进位
struct ListNode *p, *q; //设置l1和l2的游标指针
p = l1;
q = l2;
struct ListNode *get, *s, *t; //设置返回链表的头指针和拼接借口的记录指针
//读取第一位(本题给出链表不附带空的head头节点)
s = (struct ListNode *)malloc(sizeof(structListNode));
s -> next = NULL;
get = s;
s -> val = p -> val + q -> val;
if(s -> val >9) //记录和处理第一位的进位
{
s -> val %= 10;
add = 1;
}
//读取剩余的l1、l2
while(p -> next !=NULL && q -> next !=NULL)
{
p = p -> next; //处理输入链表的记录指针
q = q -> next;
t = (struct ListNode *)malloc(sizeof(structListNode));
t -> next = NULL;
t -> val = p -> val + q -> val + add;
add = 0; //记录和处理第二位的进位
if(t -> val >9)
{
t -> val %= 10;
add = 1;
}
s -> next = t; //处理返回链表的记录指针
s = s -> next;
}
//处理最后一个进位
//当l1没有读完,l2已经读完时
if(p -> next !=NULL && q -> next ==NULL)
while(p -> next != NULL)
{
p = p -> next; //处理输入链表的记录指针
t = (struct ListNode *)malloc(sizeof(structListNode));
t -> next = NULL;
t -> val = p -> val + add;
add = 0; //记录和处理第二位的进位
if(t -> val > 9)
{
t -> val %= 10;
add = 1;
}
s -> next = t; //处理返回链表的记录指针
s = s -> next;
}
//当l2没有读完,l1已经读完时
if(p -> next ==NULL && q -> next !=NULL)
while(q -> next != NULL)
{
q = q -> next; //处理输入链表的记录指针
t = (struct ListNode *)malloc(sizeof(structListNode));
t -> next = NULL;
t -> val = q -> val + add;
add = 0; //记录和处理第二位的进位
if(t -> val > 9)
{
t -> val %= 10;
add = 1;
}
s -> next = t; //处理返回链表的记录指针
s = s -> next;
}
//当l1和l2都读完时
if(p -> next ==NULL && q -> next ==NULL)
if(add == 1)
{
t = (struct ListNode *)malloc(sizeof(structListNode));
t -> next = NULL;
t -> val = add;
s -> next = t;
}
return get;
}
- LeetCode-2-Add Two Nuns(C语言实现)
- [C语言][LeetCode][2]Add Two Numbers
- leetcode 2:Add Two Numbers(C语言)
- leetcode 2. Add Two Numbers C语言实现
- 【LeetCode】2. Add Two Numbers C语言
- Leetcode c语言-Add Two Numbers
- 【LeetCode】Add Two Numbers Go语言实现
- C实现 LeetCode->Add Two Numbers
- 【leetcode-2】Add Two Numbers(C)
- [LeetCode#2][C]Add Two Numbers
- 【leetcode 2】 Add Two Numbers(C++)
- LeetCode(2) Add Two Numbers实现
- * LeetCode【2】. Add Two Numbers--java实现
- 【LeetCode编程学习(C语言)】2.Add Two Numbers
- 【LeetCode】 445. Add Two Numbers II C语言
- 【LeetCode算法练习(C语言)】Add Two Numbers
- [leetcode](Add Binary C语言实现)
- leetcode Add Digits 之C语言实现
- pytorch学习笔记(十七):python 端扩展 pytorch
- 手写死锁
- 解决在eclipse中删除tomcat server后导致无法重新添加服务器的问题
- ubuntu下忘记mysql密码
- mysql could not read contents of failed to open no such file or directory
- LeetCode-2-Add Two Nuns(C语言实现)
- Ubuntu远程连接MySQL(connection refused)解决方法
- 使用Spring Data Redis操作Redis(一) 很全面
- Redis之——jedis高版本的JedisPoolConfig没有maxActive和maxWait
- 使用springbootdatajpa遇到的性能相关问题
- 在LLVM中编写pass的详细教程(4)
- Reinforcement Learning Note: Concept and MDP
- 机器是否会取代人类工作
- LeetCode: Merge Two Sorted Lists, Remove Duplicates/Element, strStr()