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;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值