您的位置:首页 > 其它

LeetCode(2) Add Two Numbers实现

2015-02-25 22:12 441 查看
题目:https://oj.leetcode.com/problems/add-two-numbers/

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
实现两个链表的数字累加,即243+564=708

解决思路:

直接遍历列表,从左向右累加,注意进位问题即可

实现:

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		//返回的结果
		ListNode res = new ListNode(0);
		//左值
		int leftVal;
		//右值
		int rightVal;
		//是否进位
		boolean isCarry = false;
		//判断是否是第一次计算,用于保留指针
		ListNode leftNext = l1;
		ListNode rightNext = l2;
		ListNode curNode = res;
		while(leftNext != null || rightNext != null || isCarry){
			if(curNode.next == null){
				curNode.next = new ListNode(0); 
				curNode = curNode.next;
			}
			//优化时可直接拼接 ,即其中一边的节点已经计算完,后面可以直接把指针指向剩下的部分  
			leftVal = 0;
			if(leftNext != null){
				leftVal = leftNext.val;
				leftNext = leftNext.next;
			}
			rightVal = 0;
			if(rightNext != null){
				rightVal = rightNext.val;
				rightNext = rightNext.next;
			}
			int resVal = leftVal + rightVal;
			//把上一次的进位加进来
			if(isCarry){
				resVal = resVal + 1;
				isCarry = false;
			}
			if(resVal >= 10){
				isCarry = true;
				resVal = resVal % 10;
			}
			curNode.val = resVal;
		}
		return res.next;
	}


OJ测试:

通过

调试例子:

public static void main(String[] args) {
		AddTwoNumbers atn = new AddTwoNumbers();
		ListNode l1 = atn.new ListNode(2);
		l1.next = atn.new ListNode(4);
		l1.next.next = atn.new ListNode(3);
		l1.next.next.next = atn.new ListNode(9);
		
		ListNode l2 = atn.new ListNode(5);
		l2.next = atn.new ListNode(6);
		l2.next.next = atn.new ListNode(4);
		l2.next.next.next = atn.new ListNode(4);
		System.out.println(l1);
		System.out.println(l2);
		
		ListNode res = atn.addTwoNumbers(l1, l2);
		System.out.println(res);
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: