重拾编程之路--jeetcode(java)--Add Two Numbers


 * Definition for singly-linked list. public class ListNode { int val; ListNode
 * next; ListNode(int x) { val = x; } }

 * 题目如下: You are given two linked lists representing two non-negative numbers.
 * The digits are stored in reverse order and each of their nodes contain a
 * single digit. Add the two numbers and return it as a linked list.
 * 有两个链表作为输入,它们表示逆序的两个非负数。如下面的两个链表表示的是342和465这两个数。
 * 你需要计算它们的和并且用同样的方式逆序输出。如342+465 = 807,你需要把结果表达为7 ->0 ->8 Input: (2 -> 4 -> 3)
 * + (5 -> 6 -> 4) Output: 7 -> 0 -> 8



解题思路:

取一个标记mark记录是否有进位,进位记为1否则为0;

1)先以第一条链表为基准,以相同顺序遍历第二条链表;计算相同节点值的和;


      循环:

  {   1、 若第二条链表节点不为空,计算节点值和;

            1.1判断sum是否大于10,若大于10,结果节点值val=sum-10,mark=1;增加结果链表节点

                  若小于10,val=sum,增加结果链表节点;继续遍历两条链表;

     2.、第二条链表节点为空,只遍历第一条链表

            重复1.1的操作

}

2)判断第二条连边是否遍历完全

      重复1.1的操作

3)检查标记Mark是否为1

     mark=1,则在结果,增加结果链表节点;val=1.


public class C_addTwoNumbers {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		if (l1 == null && l2 == null) {
			return null;
		}
		ListNode re = new ListNode(0);
		ListNode h1 = new ListNode(0);
		ListNode h2 = new ListNode(0);
		h1.next = l1;
		h2.next = l2;
		ListNode p1 = h1;
		ListNode p2 = h2;
		ListNode p3 = re;
		int mark = 0;
		while (p1.next != null) {
			if (p2.next != null) {
				int sum = p1.next.val + p2.next.val + mark;// mark;
				ListNode node = new ListNode(0);
				if (sum < 10) {
					node.val = sum;
					p3.next = node;
					p3 = p3.next;
					p1 = p1.next;
					p2 = p2.next;
					mark = 0;
				} else {
					node.val = sum - 10;
					p3.next = node;
					p3 = p3.next;
					p1 = p1.next;
					p2 = p2.next;
					mark = 1;
				}
			} else {
				int sum = p1.next.val + mark;
				ListNode node = new ListNode(0);
				if (sum < 10) {//检查是否有进位
					node.val = sum;
					p3.next = node;
					p3 = p3.next;
					p1 = p1.next;
					mark = 0;
				} else {
					node.val = sum - 10;
					p3.next = node;
					p3=p3.next;
					p1 = p1.next;
				}
			}
		}
		// 验证第二条链表是否读完;
		if (p2.next != null) {
			while (p2.next != null) {
				int sum = p2.next.val + mark;
				if (sum < 10) {
					ListNode node = new ListNode(0);
					node.val = sum;
					p3.next = node;
					p3 = p3.next;
					p2 = p2.next;
					mark = 0;
				} else {
					ListNode node = new ListNode(0);
					node.val = sum - 10;
					p3.next = node;
					p3 = p3.next;
					p2 = p2.next;
					mark = 1;
				}
			}
		}
		// 两条链表都已经读完,验证是否还有进位的值
		if (mark != 0) {
			ListNode node = new ListNode(0);
			node.val = mark;
			p3.next = node;
			p3 = p3.next;
			mark = 0;

		}
		return re.next;
	}
}


你可能感兴趣的:(JeetCode)