File tree Expand file tree Collapse file tree 1 file changed +8
-102
lines changed Expand file tree Collapse file tree 1 file changed +8
-102
lines changed Original file line number Diff line number Diff line change 1- #include <stdio.h>
2- #include <stdlib.h>
3- #include <string.h>
4-
5- /* Definition for singly-linked list. */
6- struct ListNode {
7- int val ;
8- struct ListNode * next ;
9- };
10-
11- static struct ListNode * addTwoNumbers (struct ListNode * l1 , struct ListNode * l2 )
12- {
13- int carry = 0 ;
14- struct ListNode dummy ;
15- struct ListNode * p = l1 , * prev = & dummy ;
16-
17- dummy .next = p ;
18- while (l1 != NULL || l2 != NULL ) {
19- int sum = 0 ;
20-
21- if (l1 != NULL ) {
22- sum += l1 -> val ;
23- l1 = l1 -> next ;
24- }
25-
26- if (l2 != NULL ) {
27- if (p == NULL ) {
28- /* l2 longer than l1 */
29- prev -> next = l2 ;
30- p = l2 ;
31- }
32- sum += l2 -> val ;
33- l2 = l2 -> next ;
34- }
35-
36- sum += carry ;
37- carry = sum / 10 ;
38- p -> val = sum % 10 ;
39- prev = p ;
40- p = p -> next ;
41- }
42-
43- if (carry ) {
44- p = malloc (sizeof (* p ));
45- p -> val = carry ;
46- p -> next = NULL ;
47- prev -> next = p ;
48- }
49-
50- return dummy .next ;
51- }
52-
53- static struct ListNode * node_build (const char * digits )
54- {
55- struct ListNode * res , * p , * prev ;
56- int first = 1 ;
57- int len = strlen (digits );
58- const char * c = digits + len - 1 ;
59- prev = NULL ;
60- while (len -- > 0 ) {
61- p = malloc (sizeof (* p ));
62- if (first ) {
63- first = 0 ;
64- res = p ;
65- }
66- p -> val = * c -- - '0' ;
67- p -> next = NULL ;
68- if (prev != NULL ) {
69- prev -> next = p ;
70- }
71- prev = p ;
72- }
73-
74- return res ;
75- }
76-
77- static void show (struct ListNode * ln )
78- {
79- int sum = 0 , factor = 1 ;
80- while (ln != NULL ) {
81- sum += ln -> val * factor ;
82- factor *= 10 ;
83- ln = ln -> next ;
84- }
85- printf ("%d\n" , sum );
86- }
87-
88- int main (int argc , char * * argv )
89- {
90- if (argc < 3 ) {
91- fprintf (stderr , "Usage: ./test n1 n2\n" );
92- exit (-1 );
93- }
94-
95- struct ListNode * l1 = node_build (argv [1 ]);
96- struct ListNode * l2 = node_build (argv [2 ]);
97- struct ListNode * res = addTwoNumbers (l1 , l2 );
98- show (l1 );
99- show (l2 );
100- show (res );
101- return 0 ;
102- }
1+ #include <stdi.h>
2+ int main ()
3+ {
4+ int a ,b ,sum ;
5+ printf ("enter numbers\n" );
6+ scanf ("%d %d" ,& a & b );
7+ sum = a + b ;
8+ printf ("sum is %d" ,sum );
You can’t perform that action at this time.
0 commit comments