val:0">
赞
踩
#include<stdio.h>
#include<stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
typedef struct ListNode ListNode;
ListNode *Creat() {
ListNode* head = NULL, * tail = NULL;
int num;
scanf_s("%d", &num);
while (num != -1) {
if (!head) {
head = tail = (ListNode*)malloc(sizeof(ListNode));
if (tail) {
tail->val = num;
tail->next = NULL;
}
}else {
tail->next = (ListNode*)malloc(sizeof(ListNode));
if (tail->next) {
tail->next->val = num;
tail = tail->next;
tail->next = NULL;
}
}
scanf_s("%d", &num);
}
return head;
}
ListNode* AddTwoNum(ListNode* l1, ListNode* l2) {
ListNode* head = NULL, * tail = NULL;
int carry = 0;
while (l1 || l2) {
int n1 = l1 ? l1->val : 0;
int n2 = l2 ? l2->val : 0;
int sum = n1 + n2 + carry;
if (!head) {
head = tail = (ListNode*)malloc(sizeof(ListNode));
if (tail) {
tail->val = sum % 10;
tail->next = NULL;
}
}else {
tail->next = (ListNode*)malloc(sizeof(ListNode));
if (tail->next)
tail->next->val = sum % 10;
tail = tail->next;
tail->next = NULL;
}
carry = sum / 10;
if (l1)
l1 = l1->next;
if (l2)
l2 = l2->next;
}
if (carry) {
tail->next = (ListNode*)malloc(sizeof(ListNode));
if (tail->next) {
tail->next->val = carry;
tail = tail->next;
tail->next = NULL;
}
}
return head;
}
void Print(ListNode*l) {
ListNode* p;
p = l;
if (!l)
printf("链表为空");
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
int main() {
ListNode *l1,*l2;
l1 = Creat();
l2 = Creat();
Print(AddTwoNum(l1, l2));
return 0;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。