2. Add Two Numbers

来源:互联网 发布:新时代证券交易软件 编辑:程序博客网 时间:2024/05/22 12:58

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

这是一道链表题。head是头节点,p是用来存每次修改的节点,注意循环中要修改的应该是newnode.val,如果修改的是p.val那么最后返回的就是(7->0->8->0),多了一个零!!

class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        ListNode head = new ListNode(0);        ListNode p = head;        int flag = 0;        int temp = 0;        while((l1!=null)||(l2!=null)||(flag==1)){            ListNode newnode =new ListNode(0);            temp = flag+((l1!=null)?l1.val:0)+((l2!=null)?l2.val:0);            l1 = (l1!=null)?l1.next:l1;            l2 = (l2!=null)?l2.next:l2;            newnode.val = temp%10;            flag = temp/10;            p.next = newnode;            p = newnode;        }         return head.next;    }}


原创粉丝点击