LeetCode002 Add Two Numbers C语言
Youaregiventwolinkedlistsrepresentingtwonon-negativenumbers.Thedigitsarestoredinreverseorderandeachoftheirnodescontainasingledigit.Addthetwonumbersandreturnitasalinkedlist.Input:(2->4->3)+(5->6->4)Output:7->0->8Subscribetoseewhichcompaniesaskedthisquestion
题意:实际上就是342+465=807然后倒序输出。【一开始也没有看明白。】
参考别人的。一开始题意都没看明白。。。。。。
/***Definitionforsingly-linkedlist.*structListNode{*intval;*structListNode*next;*};*/structListNode*addTwoNumbers(structListNode*l1,structListNode*l2){structListNode*l3=(structListNode*)malloc(sizeof(structListNode));l3->val=0;l3->next=NULL;//这边因为l3是一直往后遍历的,所以返回头的话要加个head指示一下。structListNode*head=l3;l3->val=l1->val+l2->val;//while循环判断是否申请新的节点l1=l1->next;l2=l2->next;while(l1||l2||l3->val>9){l3->next=(structListNode*)malloc(sizeof(structListNode));l3->next->val=0;l3->next->next=NULL;if(l1){l3->next->val+=l1->val;l1=l1->next;}if(l2){l3->next->val+=l2->val;l2=l2->next;}if(l3->val>9){l3->next->val+=l3->val/10;l3->val=l3->val%10;}l3=l3->next;}returnhead;}
PS:主要是搞清楚有几种情况。9+8这种需要申请节点;12+9这种不等长的;
注意C语言链表的使用。。。
/***Definitionforsingly-linkedlist.*publicclassListNode{*intval;*ListNodenext;*ListNode(intx){val=x;}*}*/publicclassSolution{publicListNodeaddTwoNumbers(ListNodel1,ListNodel2){////直接模拟加法就行。先申请一个headListNodehead=newListNode(0);intcarry=0;ListNodep1=l1,p2=l2,p3=head;while(l1!=null||l2!=null){if(l1!=null){carry+=l1.val;l1=l1.next;}if(l2!=null){carry+=l2.val;l2=l2.next;}p3.next=newListNode(carry%10);p3=p3.next;carry=carry/10;}if(carry==1){p3.next=newListNode(1);}returnhead.next;}}
JAVA版本的。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。