首页 技术 正文
技术 2022年11月12日
0 收藏 337 点赞 3,239 浏览 1568 个字

221-链表求和 II

假定用一个链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。

样例

给出 6->1->7 + 2->9->5。即,617 + 295。

返回 9->1->2。即,912 。

标签

链表 高精度

思路

利用 LintCode-35.翻转链表lintcode-167-链表求和 的代码,将链表逆序后求和,之后将结果再次逆序

code

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*
* @param l1: The first list.
* @param l2: The second list.
* @return: the sum list of l1 and l2.
*/
ListNode * addLists2(ListNode * l1, ListNode * l2) {
// write your code here
l1 = reverse(l1);
l2 = reverse(l2);
return reverse(addLists(l1, l2));
} ListNode *reverse(ListNode *head) {
// write your code here
ListNode *l1 = NULL, *l2 = NULL, *l3 = NULL; l1 = head;
// 链表没有节点或有一个节点
if (l1 == NULL || l1->next == NULL) {
return l1;
}
l2 = l1->next;
// 链表有2节点
if (l2->next == NULL) {
l2->next = l1;
l1->next = NULL;
return l2;
}
l3 = l2->next;
// 链表有3个以上节点
if (l2->next != NULL) {
while (l2 != l3) {
l2->next = l1;
if (l1 == head)
l1->next = NULL;
l1 = l2;
l2 = l3; if (l3->next != NULL)
l3 = l3->next;
}
l2->next = l1;
return l2;
}
} ListNode *addLists(ListNode *l1, ListNode *l2) {
// write your code here
ListNode *head = new ListNode(0);
ListNode *temp = head;
int carry = 0;
while (l1 != NULL && l2 != NULL) {
int sum = l1->val + l2->val + carry;
ListNode *node = new ListNode(sum % 10);
carry = (sum >= 10);
temp->next = node;
l1 = l1->next;
l2 = l2->next;
temp = temp->next;
}
while (l1 != NULL) {
int sum = l1->val + carry;
ListNode *node = new ListNode(sum % 10);
carry = (sum >= 10);
temp->next = node;
l1 = l1->next;
temp = temp->next;
}
while (l2 != NULL) {
int sum = l2->val + carry;
ListNode *node = new ListNode(sum % 10);
carry = (sum >= 10);
temp->next = node;
l2 = l2->next;
temp = temp->next;
}
if (l1 == NULL && l2 == NULL && carry == 1) {
ListNode *node = new ListNode(carry);
temp->next = node;
}
return head->next;
}
};
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,294