7.29之单链表两数相加
作者:互联网
!两数相加
思路很简单,遍历两个链表将和放入新的链表之中,注意需要正确的处理进位。完整代码如下
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode curr = dummyHead;
ListNode p = l1;
ListNode q = l2;
int carry = 0;
while(p != null || q != null){
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
sum = sum % 10;
curr.next = new ListNode(sum);
curr = curr.next;
if (p != null) {
p = p.next;
}
if (q != null) {
q = q.next;
}
}
if(carry > 0){
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(2);
l1.next = new ListNode(4);
l1.next.next = new ListNode(3);
ListNode l2 = new ListNode(5);
l2.next = new ListNode(6);
l2.next.next = new ListNode(4);
ListNode listNode = addTwoNumbers(l1, l2);
while(listNode != null){
System.out.println(listNode.val);
listNode = listNode.next;
}
}
}
运行结果为
7
0
8
结果正确。
ps:对于链表问题,返回结果为头结点时,通常需要先初始化一个预先指针 pre,该指针的下一个节点指向真正的头结点head。
标签:单链,ListNode,表两数,int,next,l2,new,7.29,null 来源: https://www.cnblogs.com/g9420/p/13396292.html