cKK

............当你觉得自己很辛苦,说明你正在走上坡路.............坚持做自己懒得做但是正确的事情,你就能得到别人想得到却得不到的东西............

导航

(LinkedList)2. Add Two Numbers

Posted on 2016-04-11 01:19  cKK  阅读(148)  评论(0编辑  收藏  举报

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.

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 (l1 == null)
			return l2;
		if (l2 == null)                  //这题看起来简单,但是花了很长时间啊,链表要遍历几次,但是这样写代码最短?实在不想再写了
			return l1;
		int temp = 0;
		ListNode p = l1;
		ListNode q = l2;
		ListNode longList = l1;
		ListNode la = l1;
		while (p != null && q != null) {
			p = p.next;
			q = q.next;
		}
		if (q == null) {
			q = l1;
			p = l2;
			longList = l1;
		} else {
			q = l2;
			p = l1;
			longList = l2;
		}
		while (p != null && q != null) {
			if (p.val + q.val + temp >= 10) {
				q.val = p.val + q.val + temp - 10;
				temp = 1;
			} else {
				q.val = q.val + p.val + temp;
				temp = 0;
			}
			p = p.next;
			q = q.next;
		}
		while (q != null) {
			if (q.val + temp >= 10) {
				q.val = q.val + temp - 10;
				temp = 1;
			} else {
				q.val = q.val + temp;
				temp = 0;
			}
			q = q.next;
		}
		if (temp == 1) {
			ListNode last = new ListNode(1);
			last.next = null;
			p = longList;
			while (p.next!= null)
				p = p.next;
			la = p;
			la.next = last;
		}

		return longList;
    }
}