leetcode - 面试题 02.05. 链表求和
题目

代码
#include <iostream>
#include <vector>
using namespace std;
typedef struct ListNode {
int val;
struct ListNode *next;
}ListNode, *LinkList;
void create(LinkList &head){
int n;
cin>>n;
head = new ListNode;
head->next = NULL;
ListNode *tail = head;
for(int i = 0; i < n; i++){
ListNode *p = new ListNode;
cin>>p->val;
p->next = NULL;
tail->next = p;
tail = p;
}
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int sum = 0, flag = 0, num = 0;
int x, y;
ListNode *head = new ListNode;
head->next = NULL;
ListNode *tail = head;
while(l1 || l2 || flag){
if(l1){
x = l1->val;
l1 = l1->next;
}else{
x = 0;
}
if(l2){
y = l2->val;
l2 = l2->next;
}else{
y = 0;
}
sum = x + y + flag;
flag = sum / 10;
num = sum % 10;
ListNode *p = new ListNode;
p->val = num;
p->next = NULL;
tail->next = p;
tail = p;
}
return head->next;
}
int main(){
ListNode *l1, *l2, *res;
create(l1);
create(l2);
l1 = l1->next;
l2 = l2->next;
res = addTwoNumbers(l1, l2);
while(res){
cout<<res->val<<" ";
res = res->next;
}
return 0;
}
最后
以上就是聪明金针菇最近收集整理的关于leetcode - 面试题 02.05. 链表求和leetcode - 面试题 02.05. 链表求和的全部内容,更多相关leetcode内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复