zoukankan      html  css  js  c++  java
  • 利用链表计算两个数字之和

    #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;
    }
  • 相关阅读:
    无序数组求第K大/第K小的数
    [洛谷][二分搜索]进击的奶牛
    [015]向下类型转换和向上类型转换
    [014]析构函数为虚函数的注意事项
    [013]函数重载--int*和void*的匹配优先级
    [012]链表笔记--在链表中插入一个节点
    [011]链表笔记--删除一个链表节点
    [002]链表笔记--编程实现一个单链表的创建/测长/打印
    [C++]对象的销毁机制
    [011]默认实参
  • 原文地址:https://www.cnblogs.com/lilideng/p/11281163.html
Copyright © 2011-2022 走看看