分析: 定义三个链表,两个链表负责两组数据的存储,第三个链表负责存储结果,前两个链表每个对应位置上的数据相加,注意进位处理,以及如果两个链表不等长的情况。
代码实现:
class Solution3 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null)
return l2;
if(l2 == null)
return l1;
ListNode head = new ListNode(0);
ListNode cur = head;
int num = 0;
int flag = 0;
while(l1!=null || l2!=null || flag!=0){
int num1 = 0;
int num2 = 0;
if(l1 != null){
num1 = l1.data;
l1 = l1.next;
}
if(l2 != null){
num2 = l2.data;
l2 = l2.next;
}
num = (num1 + num2 + flag) % 10;
flag = (num1 + num2 + flag) / 10;
ListNode t = new ListNode(num);
cur.next = t;
cur = cur.next;
}
return head.next;
}
}
public class ListNodeAdd{
public static void main(String[] args){
Solution3 s = new Solution3();
ListNode l1 = null;
ListNode l11 = new ListNode(7);
ListNode l12 = new ListNode(1);
ListNode l13 = new ListNode(6);
l1 = l11;
l11.next = l12;
l12.next = l13;
ListNode l2 = null;
ListNode l21 = new ListNode(5);
ListNode l22 = new ListNode(9);
ListNode l23 = new ListNode(2);
l2 = l21;
l21.next = l22;
l22.next = l23;
System.out.println(l2);
ListNode lnew = s.addTwoNumbers(l1,l2);
}
}
public class ListNode {
public int data;
public ListNode next;
public ListNode(int data){
this.data = data;
}
}
|