利用链表计算两个数字之和

#include <stdio.h>
typedef struct {
    int data;
    struct Node* next;
}Node;
Node* CreateNode(int value) {
    Node* temp = (Node*)malloc(sizeof(Node));
    temp->data=value;
    temp->next=NULL;
    return temp;
}
Node* InsertNodeFromHead(Node* head, int value){
    Node* p=CreateNode(value);
    if(head==NULL) {
        head=p;
    } else {
        p->next=head;
        head=p;
    }
    return head;
}
void PrintLinkedList(Node* head) {
    if(head==NULL) {
        printf("Current linked list is empty.");
    }
    else {
        Node* p=head;
        while(p) {
            printf(" %d =>", p->data);
            p=p->next;
        }
    }
    printf(" NULL ");
}
Node* AddSumFromLinkedList(Node* head1, Node* head2) {
    Node* head3=NULL, *p1=head1, *p2=head2;
    int addone = 0, sum = 0;
    while(p1 || p2) {
        sum = (p1==NULL?0:p1->data) + (p2==NULL?0:p2->data);
        head3=InsertNodeFromHead(head3, sum%10+addone);
        addone = 0;
        addone = sum>=10?1:0;
        if(p1) p1=p1->next;
        if(p2) p2=p2->next;
    }
    if(addone==1) {
        head3=InsertNodeFromHead(head3, addone);
    }
    return head3;
}
int main()
{
    Node* head1=NULL;
    Node* head2=NULL;
    Node* head3=NULL;
    head1=InsertNodeFromHead(head1,8);
    head1=InsertNodeFromHead(head1,8);
    head1=InsertNodeFromHead(head1,8);
    PrintLinkedList(head1);
   
    head2=InsertNodeFromHead(head2,8);
    head2=InsertNodeFromHead(head2,8);
    head2=InsertNodeFromHead(head2,8);
    PrintLinkedList(head2);
   
    head3=AddSumFromLinkedList(head1, head2);
    PrintLinkedList(head3);
    return 0;
}
原文地址:https://www.cnblogs.com/lilideng/p/11281163.html