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

mac2022-06-30  120

#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\n"); } 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+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

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)