Contents
  1. 1. Add Two Numbers
    1. 1.1. input
  2. 2. output

链表的操作,add的时候,先把p.next赋值(p.next.next指向空),然后p = p.next移动指针; 删除的时候用一个p指向原链表t,temp先指向要删除节点的t.next, 然后p.next = temp, 然后释放temp。
写的很艰难。。。

Add Two Numbers

输入2个链表,由低位到高位,实现相加操作。

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

input

[2,4,3]
[5,6,4]

output

[7,0,8]

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
         if( null == l1 ){
                return l2;
            }
        if( null == l2){
                return l1;
            }
        int temp = 0;
        ListNode res = new ListNode(0);
        ListNode p1 = l1, p2 = l2, p3 = res;
        while(p1 != null || p2 != null){ //开始移动指针
            if(null != p1){
                temp += p1.val;
                p1 = p1.next;    
            }

            if(null != p2){
                temp += p2.val;
                p2 = p2.next;      
            }

            p3.val = temp % 10; // p1 + p2
            if(null != p1 || null != p2){
                p3.next = new ListNode(temp / 10); //如果l1,p2没到头,则需要继续计算
                p3 = p3.next; 
            }
            temp = temp / 10;// 如果需要进位,temp为1
        }
        if (temp == 1){
            p3.next = new ListNode(1); //最后可能需要进位
        }
        return res;
    }
}
Contents
  1. 1. Add Two Numbers
    1. 1.1. input
  2. 2. output