题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
// 反转链表
ListNode reverse(ListNode head) {
if (head == null)
return head;
ListNode cur = head;
ListNode node = null;
while (cur != null) {
ListNode tail = cur.next;
cur.next = node;
node = cur;
cur = tail;
}
return node;
}
public ListNode addInList (ListNode l1, ListNode l2) {
l1 = reverse(l1);
l2 = reverse(l2);
ListNode head = null, tail = null;
int carry = 0; //进位置 carry
while (l1 != null || l2 != null) {
int n1 = l1 != null ? l1.val : 0;
int n2 = l2 != null ? l2.val : 0;
int sum = n1 + n2 + carry;
if (head == null) {
head = tail = new ListNode(sum % 10);
} else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = sum / 10;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (carry > 0) {
tail.next = new ListNode(carry);
}
head = reverse(head);
return head;
}
}
这道题和LeetCode第二道题其实是一样的,把链表反转相加时,从最低位到最高位逐位处理,并将结果按顺序添加到结果链表中。
进位值为 carry,则它们的和为 n1+n2+carry。
class ListNodeSolution {
public class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public static ListNode createList(int[] values) {
ListNode head = new ListNode(values[0]);
ListNode current = head;
for (int i = 1; i < values.length; i++) {
current.next = new ListNode(values[i]);
current = current.next;
}
return head;
}
public static void printList(ListNode node) {
while (node != null) {
System.out.print(node.val);
if (node.next != null) {
System.out.print("->");
}
node = node.next;
}
System.out.println();
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, tail = null;
int carry = 0;
while(l1!=null || l2!=null){
int n1 = l1!=null ? l1.val : 0;
int n2 = l2 !=null ? l2.val : 0;
int sum = n1+n2 + carry;
if(head == null){
head = tail = new ListNode(sum % 10);
}else{
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = sum / 10;
if(l1!=null){
l1 = l1.next;
}
if(l2!=null){
l2 = l2.next;
}
}
if(carry > 0){
tail.next = new ListNode(carry);
}
return head;
}
public static void main(String[] args) {
ListNode l1 = createList(new int[]{2, 4, 3});
ListNode l2 = createList(new int[]{5, 6, 4});
printList(l1);
printList(l2);
ListNodeSolution solution = new ListNodeSolution();
ListNode listNode = solution.addTwoNumbers(l1, l2);
printList(listNode);
}
}
格力公司福利 319人发布
