Comprendí por los detalles de la pregunta que la recursividad es una posibilidad. Así que aquí hay un algoritmo O (N) con O (1) espacio adicional además de guardar el resultado.
Primero encuentre la longitud de cada lista. Luego use la recursividad para sumar las 2 listas de dígitos.
Si las listas tienen longitudes diferentes, hay 2 casos:
– size (l1)> size (l2): supongamos que l2 tiene ceros a la izquierda.
– size (l1) <size (l2): agregar nodos encabeza l1 hasta que tengan el mismo tamaño porque l1 almacenará el resultado.
class Ideone {
static class Node {
int digit;
Node next;
Node(int value) {
digit = value;
next = null;
}
}
public int listLength(Node current) {
return current == null ? 0 : 1 + listLength(current.next);
}
// The return node may have a value > 9.
public Node sumLists(Node a, int remainingA, Node b, int remainingB) {
if (a == null && b == null)
return null;
if (remainingA == remainingB) {
a.next = sumLists(a.next, remainingA-1, b.next, remainingB-1);
} else if (remainingA > remainingB) {
a.next = sumLists(a.next, remainingA-1, b, remainingB);
} else {
Node cur = a; // Add a node to the head of list A.
a = new Node(0);
a.next = sumLists(cur, remainingA, b.next, remainingB-1);
}
if (a.next != null && a.next.digit > 9) {
a.next.digit %= 10;
a.digit++; // Carry.
}
if (remainingA <= remainingB) { // Does list b have a digit?
a.digit += b.digit;
}
return a;
}
// Sums 2 lists. Saves result in the first one.
public Node sumLists(Node a, Node b) {
int lengthA = listLength(a);
int lengthB = listLength(b);
a = sumLists(a, lengthA, b, lengthB);
if (a != null && a.digit > 9) {
Node cur = a;
cur.digit %= 10;
a = new Node(1);
a.next = cur;
}
return a;
}
}
- ¿Pueden los candidatos en entrevistas de programación realmente escribir código en el acto?
- Para un proyecto de entrevista de codificación, ¿es mejor usar solo la biblioteca estándar de un idioma o está bien incorporar herramientas de biblioteca no estándar?
- ¿Cómo se preparan otros ingenieros de software senior para codificar entrevistas?
- Cómo abordar sistemáticamente los problemas de retroceso
- Cómo asegurarse de que me he preparado exhaustivamente para las ubicaciones