您好,欢迎来到爱玩科技网。
搜索
您的当前位置:首页C语言数据结构与算法--两数相加

C语言数据结构与算法--两数相加

来源:爱玩科技网
/*server.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Definition for singly-linked list.
struct ListNode {
    int val;
    struct ListNode* next;
};

typedef struct ListNode ListNode;


ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
    ListNode* dumy;
    ListNode* temp;
    dumy = (ListNode *)malloc(sizeof(ListNode));
    dumy->next = NULL;
    temp = dumy;

    int result = 0;
    int tempRes = 0;
    int flag = 0;

    while (l1 != NULL || l2 != NULL) {
        result = 0;
        if (l1 != NULL) {
            result += l1->val;
            l1 = l1->next;
        }

        if (l2 != NULL) {
            result += l2->val;
            l2 = l2->next;
        }

        tempRes = (result + flag) % 10;
        flag = (result + flag) / 10;

        ListNode* current = (ListNode *)malloc(sizeof(ListNode));
        current->val = tempRes;
        temp->next = current;
        temp = temp->next;
    }

    if (flag > 0) {
        ListNode* final = (ListNode *)malloc(sizeof(ListNode));
        final->val = flag;
        temp->next = final;
        temp = temp->next;
    }

    temp->next = NULL;
    return dumy;
}

ListNode* AddListNode(ListNode* head, int value)
{
    ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
    temp->val = value;
    temp->next = head->next;
    head->next = temp;
    temp = NULL;
    return head;
}

void ShowListNode(ListNode* head)
{
    ListNode* temp = head->next;
    while (temp != NULL) {
        printf("the listnode value is %d\n", temp->val);
        temp = temp->next;
    }
}


int main()
{
    int i;
    int nums1[3] = {2, 4, 3};
    int nums2[3] = {5, 6, 4};

    ListNode* L1 = (ListNode*)malloc(sizeof(ListNode));
    L1->next = NULL;
    for (i = 0; i < 3; i++) {
        L1 = AddListNode(L1, nums1[i]);
    }
    ShowListNode(L1);

    ListNode* L2 = (ListNode*)malloc(sizeof(ListNode));
    L2->next = NULL;
    for (i = 0; i < 3; i++) {
        L2 = AddListNode(L2, nums2[i]);
    }
    ShowListNode(L2);

    ListNode* resultListNode = (ListNode*)malloc(sizeof(ListNode));
    resultListNode->next = NULL;
    resultListNode = addTwoNumbers(L1->next, L2->next);
    ShowListNode(resultListNode);

    free (L1);
    free (L2);
    free(resultListNode);
    return 0;
}

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- aiwanbo.com 版权所有 赣ICP备2024042808号-3

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务