lintcode-【简单题】链表求和
题目:
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
样例:
给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
答案:
从头到尾按链表顺序遍历相加就行啦,如果加到最后,进位不为0,还需要另外添加一个节点。
public ListNode addTwoNumbers(ListNode first, ListNode second) {
if(first==null)
return second;
if(second==null)
return first;
int sum=0;//first和second对应结点的和,值为(0-9);
int carry=0;//first和second对应结点求和后对应的进位,值为(0或1);
ListNode head=new ListNode(0);
ListNode cur=head;
while(first != null||second != null||carry != 0)
{
int num1=0;
int num2=0;
if(first!=null)
{
num1=first.val;
first=first.next;
}
if(second!=null)
{
num2=second.val;
second=second.next;
}
sum=(carry+num1+num2)%10;
ListNode temp=new ListNode(sum);
cur.next=temp;
cur=cur.next;
carry=(carry+num1+num2)/10;
}
return head.next;
}
https://blog.csdn.net/jingsuwen1/article/details/51355580
https://www.cnblogs.com/Shirlies/p/5219343.html
最后
以上就是自信冬天最近收集整理的关于链表求和的全部内容,更多相关链表求和内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复