首页 > 学院 > 开发设计 > 正文

Leetcode Linked List Problem 链表问题合集

2019-11-11 01:19:51
字体:
来源:转载
供稿:网友

1. Leet Code OJ 2. Add Two Numbers

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

您将获得两个非空链接列表,表示两个非负整数。 数字以相反的顺序存储,并且它们的每个节点包含单个数字。 添加两个数字并将其作为链接列表返回。

您可以假定这两个数字不包含任何前导零,除了数字0本身。

输入:(2→4→3)+(5→6→4) 输出:7 - > 0 - > 8

代码:

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode node = new ListNode(0); if(l1 == null && l2 == null) return l1; back(node, l1, l2); return node; } public void back(ListNode result, ListNode l1, ListNode l2){ if(l1 != null) result.val += l1.val; else l1 = new ListNode(0); if(l2 != null) result.val += l2.val; else l2 = new ListNode(0); ListNode node = new ListNode(0); if(result.val >= 10){//说明会下一个节点值至少为1 result.val = result.val % 10; node.val = 1; result.next = node; } if( (l1.next != null || l2.next != null)){ result.next = node; back(result.next, l1.next, l2.next); } }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表