cci-Q2.4 链表的值相加
来源:互联网 发布:淘宝的试用中心在哪 编辑:程序博客网 时间:2024/05/22 04:27
原文:
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 –> 1 –> 5), (5 –> 9 –> 2)
Output: 8 –> 0 –> 8
译文:
你有两个由单链表表示的数。每个结点代表其中的一位数字。数字的存储是逆序的, 也就是说个位位于链表的表头。写一函数使这两个数相加并返回结果,结果也由链表表示。
例子:(3 –> 1 –> 5), (5 –> 9 –> 2)
输入:8 –> 0 –> 8
使用递归,如果anode和bnode不同时为空,则new一个新的morenode,morenode.data=anode.data+bnode.data+carry(上一次相加的进位)。
public static void main(String args[]) { // a = 815 int a[] = {5, 1, 8,}; // b = 3186 int b[] = {6, 8, 1, 3}; LinkedListNode aNode = arrToList(a); LinkedListNode bNode = arrToList(b); //output aNode: 518 printList(aNode); //output bNode 6813 printList(bNode); LinkedListNode result = add(aNode, bNode, 0); //output result 1004 printList(result); } public static void printList(LinkedListNode a) { LinkedListNode tmp = a; while (tmp != null) { System.out.println(tmp.data); tmp = tmp.next; }; System.out.println(""); } public static LinkedListNode arrToList(int[] a) { LinkedListNode node = null; LinkedListNode tmp = null; for (int i = 0; i < a.length; i++) { LinkedListNode next = new LinkedListNode(a[i]); if (i == 0) { node = tmp = next; continue; } tmp.next = next; tmp = next; } return node; } public static LinkedListNode add(LinkedListNode a, LinkedListNode b, int carry) { if (a == null && b == null) { return null; } LinkedListNode result = new LinkedListNode(carry); int value = carry; if (a != null) { value += a.data; } if (b != null) { value += b.data; } result.data = value % 10; LinkedListNode more = add(a == null ? null : a.next, b == null ? null : b.next, value > 9 ? 1 : 0); result.next = more; return result; }
- cci-Q2.4 链表的值相加
- cci-Q2.5 寻找环形链表的起点
- cci-Q2.2 链表倒数第n节点值
- cci-Q2.3 只给出中间节点,删除链表中间节点
- cci-Q2.1 未排序链表去重
- Q2.4
- CCI 2.5 链表整数求和
- CCI 2.7 链表是否为回文
- CCI 复习笔记 4
- CCI 2.4 以某数为基准分割链表
- Q2.4 Partition List
- 链表实现的多项式相加相乘
- 利用链表计算多项式的相加
- 利用链表计算多项式的相加
- 将两个链表的元素相加
- 两个随机长度的链表相加
- Q2 兰德的竞争优势
- 多项式相加链表
- 浅谈Linux PCI设备驱动(一)
- 【转】麻瓜项目:家庭能源消耗管理之“网络电能表”(乐联网有线网络版
- 泛泰长短信修改教程(供其他泛泰机型参考)
- Android DVM
- iOS 5与iOS 6的 low-memory 处理
- cci-Q2.4 链表的值相加
- Python100例——第八章----数字0~9的奇妙变换
- 在iOS上绘制自然的签名
- Discovery学习之路--前言
- Python100例——第九章----数的变换
- C语言结构体的字节对齐原则
- Floyd 算法原理
- HDU-1008 电梯啊
- iOS开发——图片转PDF的实现方法