Problem Description:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
分析题目:该题实际上就是求两个链表相加,比较简单,只需要注意一下链表位数不等与进位的问题即可。
源程序(包含输入与输出):
/*
**
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode* List;
struct ListNode {
int val;
struct ListNode *next;
};
void Print(List L);
List ReadInput(void);
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2);
int main()
{
List l1,l2,l;
l1 = ReadInput();
l2 = ReadInput();
// Print(l1);
// Print(l2);
l = addTwoNumbers( l1, l2);
Print(l);
return 0;
}
List ReadInput(void)
{
List L,P,t;
L = (List)malloc(sizeof(struct ListNode));
P = L;
scanf("%d",&P->val);
for( ; getchar() != '\n'; )
{
t = P;
P = (List)malloc(sizeof(struct ListNode));
t->next = P;
scanf("%d",&P->val);
}
P->next = NULL;
return L;
}
void Print(List L)
{
List P=L;
for(; P!=NULL; P = P->next)
printf("%d ",P->val);
printf("\n");
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *p1, *p2 , *l, *t, *p;
int c=0; /* 进位 */
l = (struct ListNode*)malloc(sizeof(struct ListNode));
p = l;
for(p1 = l1, p2 = l2; p1 != NULL && p2 != NULL; p1 = p1->next, p2 = p2->next)
{
p->val = p1->val + p2->val + c;
// printf("%d p %d p1 %d p2\n",p->val,p1->val,p2->val);
t = p;
p = (struct ListNode*)malloc(sizeof(struct ListNode));
t->next = p;
c = 0;
if(t->val > 9)
{
t->val -= 10;
c = 1;
}
}
/*
** p1=NULL, p1的位数小于p2
** p+p2;
*/
if( !p1 )
{
for( ; p2 != NULL; p2 = p2->next)
{
p->val = p2->val + c;
t = p;
p = (struct ListNode*)malloc(sizeof(struct ListNode));
t->next = p;
if(t->val > 9) {
c=1; /* 若进位则加1 */
t->val -= 10;
}
else c = 0;
}
}
/*
** p2=NULL, p2的位数小于p1
** p+p1;
*/
if( !p2 )
{
for( ; p1 != NULL; p1 = p1->next)
{
p->val = p1->val + c;
t = p;
p = (struct ListNode*)malloc(sizeof(struct ListNode));
t->next = p;
if(t->val > 9) {
c=1; /* 若进位则加1 */
t->val -= 10;
}
else c = 0;
}
}
/*
** p1,p2位数一样,但是最高位进位
*/
if(c)
{
p->val = c;
t = p;
p = (struct ListNode*)malloc(sizeof(struct ListNode));
t->next = p;
}
free(p);
t->next = NULL;
return l;
}

本文介绍了一种使用链表表示非负整数并进行加法运算的方法。通过C语言实现,详细展示了如何处理不同长度链表的加法及进位问题。
811

被折叠的 条评论
为什么被折叠?



