算法系列——Add Two Numbers

来源:互联网 发布:sql数据库管理下载 编辑:程序博客网 时间:2024/06/05 17:07

题目描述

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

解题思路

这道题目要求对两个链表模拟加法操作。我们可以引入一个虚拟头结点,将新生成的节点连接到头结点尾部。遍历两个链表,执行加法操作即可。注意对末尾1的处理。

程序实现

public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        if(l1==null)            return null;        if(l2==null)            return null;        ListNode p1=l1;        ListNode p2=l2;        ListNode dummyHead=new ListNode(-1);        ListNode p=dummyHead;        int d=0;        int cur=0;        while(p1!=null&&p2!=null){            cur=(p1.val+p2.val+d)%10;            d=(p1.val+p2.val+d)/10;            ListNode node=new ListNode(cur);            p.next=node;            p=p.next;            p1=p1.next;            p2=p2.next;        }        while(p1!=null){             cur=(p1.val+d)%10;            d=(p1.val+d)/10;            ListNode node=new ListNode(cur);            p.next=node;            p=p.next;            p1=p1.next;        }        while(p2!=null){            cur=(p2.val+d)%10;            d=(p2.val+d)/10;            ListNode node=new ListNode(cur);            p.next=node;            p=p.next;            p2=p2.next;        }        if(d!=0){            ListNode node=new ListNode(1);            p.next=node;        }        return dummyHead.next;    }}
原创粉丝点击