-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumbers.cpp
More file actions
executable file
·72 lines (62 loc) · 1.37 KB
/
AddTwoNumbers.cpp
File metadata and controls
executable file
·72 lines (62 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//
// AddTwoNumbers.cpp
// leetcode
//
// Created by witwolf on 5/5/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* node,*prev = NULL,*head = NULL;
int val = 0;
while(l1 || l2 || val){
if(l1){
val += l1->val;
l1 = l1->next;
}
if(l2){
val += l2->val;
l2 = l2->next;
}
node = (struct ListNode*) malloc(sizeof(struct ListNode));
node->next = NULL;
node->val = val % 10;
val = val / 10 ;
if(head == NULL){
head = node ;
prev = node;
}else{
prev->next = node;
prev = node ;
}
}
return head;
}
void print(struct ListNode *head){
while(head){
printf("%d->",head->val);
head = head->next;
}
printf("NULL\n");
}
int main(int argc,char **argv){
struct ListNode n1,n2,n3;
n1.val = 9;
n1.next = &n2;
n2.val = 8;
n2.next = &n3;
n3.val = 5;
n3.next = NULL;
print(&n1);
print(addTwoNumbers(&n1,NULL));
print(addTwoNumbers(NULL,NULL));
print(addTwoNumbers(&n1,&n1));
}