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