Leecode Add Two Numbers(Java版)

/**
 * 
 * @author WF帆少
 * @微信 13025261795
 *
 */
class Solution {
	
	public static int getListNodeLength(ListNode l) {
		int length = 0;
		while (l != null) {
			length++;
			l = l.next;
		}
		return length;
	}
	
	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		
		// 用于标记是否进位
		int flag = 0;
		
		
		
		// 获取l1,l2的结点数,谁的结点数大l3就指向哪个结点
		int l1Length = getListNodeLength(l1), 
				l2Length = getListNodeLength(l2);
		
		ListNode temp = null, l3 = null;
		if (l1Length >= l2Length) {
			l3 = l1;
			temp = l1;
		} else {
			l3 = l2;
			temp = l2;
		}
		
		while (l1 != null || l2 != null) {
			
			if (l1 == null) {
				l1 = new ListNode(0);
			}
			if (l2 == null) {
				l2 = new ListNode(0);
			}
			
			temp.val = l1.val + l2.val;
			if (temp.val >= 10) {
				temp.val -= 10;
				// 判断最高位结点的进位结点是否为空
				if (temp.next != null) {
					temp.next.val++;
				} else {
					temp.next = new ListNode(1);
				}
			} 
			temp = temp.next;
			l1 = l1.next;
			l2 = l2.next;
		}
		return l3;
	}
	
	
}
原创文章 28 获赞 52 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq1123642601/article/details/86570104