2. Add Two Numbers
2016-11-17 14:43
309 查看
Add Two Numbers
Difficulty: Medium
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
Difficulty: Medium
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
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
/* * 分析:题目中给出两个链表,然后相加,但是一旦相加超过10,就会向下一个节点进位,这里就需要判断如何进行进位 * @titleAddTwoSum.java * @author taojian * @date2016-11-17下午1:08:29 */ public class AddTwoSum { public static void main(String[] args) { ListNode l1=new ListNode(2); l1.next=new ListNode(4); l1.next.next=new ListNode(3); ListNode l2=new ListNode(5); l2.next=new ListNode(6); l2.next.next=new ListNode(4); /* while(l1!=null){ System.out.println(l1.val); //System.out.println(l1.next.val); l1=l1.next; }*/ AddTwoSum as=new AddTwoSum(); ListNode sum=as.addTwoNumbers(l1,l2); while(sum!=null){ System.out.println(sum.val); sum=sum.next; } } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { /* ListNode sum=new ListNode(0); ListNode list1=l1,list2=l2; while(l1.next!=null&&l2.next!=null){ sum.val=l1.val+l2.val; l1=l1.next; l2=l2.next; sum=sum.next; //以上题目没看清 } return sum;*/ //设置头节点,数据为0 ListNode head = new ListNode(0); //两个链表p,q,一个新的链表currsum用来存放p,q节点相加 ListNode list1 = l1, list2 = l2, currsum = head; int m = 0; while (list1 != null || list2 != null) { //由于链表的长度不一致,当某一个链表空的时候,应该把0置位 int x,y; if(list1!=null) x=list1.val; else x=0; if(list2!=null) y=list2.val; else y=0; //如果过了10,就会进位 int sum = m + x + y; m = sum / 10; //超过10的数取各位数 currsum.next = new ListNode(sum % 10); currsum = currsum.next; if (list1 != null) list1 = list1.next; if (list2!= null) list2 = list2.next; }//这个需要判断
if (m > 0) { currsum.next = new ListNode(m); }return head.next; } }
相关文章推荐
- Leetcode Java Add Two Numbers
- Add Two Numbers II
- LeetCode 2: Add Two Numbers (JAVA)
- leetcode--Add Two Numbers
- LeetCode # Add Two Numbers #
- LeetCode-Add Two Numbers
- [LeetCode] Add Two Numbers
- Add Two Numbers
- Java [leetcode 2] Add Two Numbers
- [leetcode]Add Two Numbers
- 2. Add Two Numbers
- LeetCode 2 Add Two Numbers
- LeetCode: 2. Add Two Numbers 【C 解题】
- LeetCode: Add Two Numbers
- [leetcode]Add Two Numbers
- [LeetCode]-algorithms-Add Two Numbers
- Leetcode Add Two Numbers
- Leetcode 2, Add Two Numbers
- leetcode#2-Add Two Numbers-java
- LeetCode:M-2. Add Two Numbers