LinkedList Add Two Numbers: LeetCode - java

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.
The linked list seems to be overwriting the nodes as far as I can tell. I did find the answer to this problem on GeeksforGeeks but I wanted help with figuring out what is wrong with my code. I also know my code is not the best in regards to optimization but any halp is accepted. Thanks!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
//ListNode head;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int x = 0;
int y = 0;
int z = 1;
while(l1 != null){
x += z*l1.val;
z*=10;
l1 = l1.next;
}
z = 1;
while(l2 != null){
y += z*l2.val;
z*=10;
l2 = l2.next;
}
int sum = x + y;
ListNode node = new ListNode(0);
while(sum > 0){
int digit = sum % 10;
ListNode n = new ListNode(digit);
while(node.next != null){
node = node.next;
}
node.next = n;
sum = sum / 10;
}
return node;
}
}
LeetCode Question

I like your solution but you have bit incomplete logic.
class Solution {
//ListNode head;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int x = 0;
int y = 0;
int z = 1;
while(l1 != null){
x += z*l1.val;
z*=10;
l1 = l1.next;
}
z = 1;
while(l2 != null){
y += z*l2.val;
z*=10;
l2 = l2.next;
}
int sum = x + y;
if (sum == 0) {
return new ListNode(0);
}
ListNode node = null, head = null;
while(sum > 0){
int digit = sum % 10;
ListNode n = new ListNode(digit);
if (node == null) {
head = node = n;
} else {
node.next = n;
node = node.next;
}
sum = sum / 10;
}
return head;
}
}
I just changed one or two things after int sum = x + y;

This is the solution in kotlin Language.
class Solution {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
var head1=l1
var head2=l2
var result:ListNode?=null
var temp:ListNode?=null
var carry=0
while(head1 != null || head2 != null)
{
var sum=carry
if(head1 != null)
{
sum += head1.`val`
head1=head1.next
}
if(head2 != null)
{
sum +=head2.`val`
head2= head2.next
}
val node= ListNode(sum%10)
carry=sum/10
if(temp== null)
{
result=node
temp=result
}
else{ temp.next=node
temp=temp.next}
}
if(carry>0){
temp!!.next=ListNode(carry)
}
return result
}
}

The solution in Java from my leetcode submission. Beats 100% of other solutions in runtime, and beats 97.3% of solutions in memory. It uses recursion of course.
/* Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int sum, carry;
sum = l1.val + l2.val;
carry = 0;
if (sum >= 10){
sum = sum - 10;
carry = 1;
}
l1.val = sum;
if(carry == 1){
if(l1.next != null) {
l1.next.val++;
}
else {
l1.next = new ListNode(carry);
}
}
if(l1.next != null && l2.next!= null) addTwoNumbers(l1.next, l2.next);
else if (l1.next!= null && l2.next == null) addTwoNumbers(l1.next, new ListNode(0));
else if (l2.next != null && l1.next == null) {
l1.next = new ListNode(0);
addTwoNumbers(l1.next, l2.next);
}
return l1;
}
}

Related

Swaping elements in likendlist for a few times java

I am trying to swap elements but the cycle is infinite.
The problem is in method change() or find().
I am just learning JAVA, so its hard to me to understand where is the mistake.
import java.util.*;
public class CustomLinkedList {
class Node{
int element;
Node next;
Node(int element){
this.element = element;
}
}
private Node first;
private Node last;
private int size;
private Node temp;
public void add(int element) {
Node newNode = new Node(element);
if(first == null) {
first = last = newNode;
} else {
last.next = newNode;
last = newNode;
}
size++;
}
public void output() {
Node current = first;
if(current == null) {
System.out.println("YOUR LIST IS EMPTY!!! ADD SOME ELEMENTS!!!");
}
else {
while(current != null) {
System.out.print("["+current.element+ "]" + " ");
current = current.next;
}
System.out.println();
}
}
public Node find(int index) {
Node current = first;
for(int i = 0; i < index; i++) {
current = current.next;
}
return current;
}
public void change(int index, int k) {
int count = 0;
while(count < k) {
Objects.checkIndex(index, size);
Node our = find(index);
temp = our.next;
our.next = our;
our = temp;
our = null;
count++;
index++;
}
}
}
Maybee, someone know how to do this.
When you swap two elements in a linked list, you actually need to modify up to three elements. For example, look at the following sub-list:
... -> a -> b -> c -> d -> ...
If you swap c and b, you get:
... -> a -> c -> b -> d -> ...
Now, the following has changed:
The next of a is now c (it was b).
The next of b is now d (it was c).
The next of c is now b (it was d).
Three nodes changed. Your code in the change() method only modifies two nodes, it forgets about node a.
Update
Possible implementation of a swap method:
/**
* Swaps the elements at the i-th and the (i-1)-th indices.
*/
public void swap(int index) {
Objects.checkIndex(index, size - 1);
if (index == 0) {
// Before swap: first -> x -> y
Node oldFirst = first;
Node x = first.next;
Node y = x.next;
// After swap: x -> first -> y
x.next = first;
first.next = y;
first = x;
// Update `last` if last two elements swapped
if (size == 2) {
last = oldFirst;
}
} else {
// Before swap: a -> b -> c -> d
Node a = find(index - 1);
Node b = a.next;
Node c = b.next;
Node d = c.next;
// After swap: a -> c -> b -> d
a.next = c;
b.next = d;
c.next = b;
// Update `last` if last two elements swapped
if (index == size - 2) {
last = b;
}
}
}

Couldn't implement binary search on linked list

i am a cse student who takes data structures course. Trying to implement binary search algorithm to my SinglyLinkedList class, somehow i've failed. Could you check it what's wrong please ?
The related method;
I've debugged and it just enters the loops this side: else if(temp.getElement() > target)
public int binarySearchLinkedList(SinglyLinkedList<E> list, E target) {
int left = 0;
int right = list.getSize();
while (left <= right) {
int mid = (left + right) / 2;
Node<E> temp = head;
for (int i = 0; i < mid - 1; i++) {
temp = temp.next;
}
if (temp.getElement() instanceof Number && target instanceof Number) {
if (Integer.parseInt(temp.getElement().toString()) == Integer.parseInt(target.toString())) {
return mid;
} else if (Integer.parseInt(temp.getElement().toString()) > Integer.parseInt(target.toString())) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
All class for better understanding;
public class SinglyLinkedList<E> {
private static class Node<E> {
private E element;
private Node<E> next;
public Node(E e, Node<E> n) {
element = e;
next = n;
}
private E getElement() {
return element;
}
private Node<E> getNext() {
return next;
}
private void setNext(Node<E> n) {
next = n;
}
}
private Node<E> head;
private Node<E> tail;
private int size;
public SinglyLinkedList() {
};
public int getSize() {
return size;
}
public void append(E e) {
if (head == null) {
head = new Node<E>(e, null);
tail = head;
size++;
return;
}
Node<E> temp = head;
while (temp != tail) {
temp = temp.next;
}
temp.setNext(tail = new Node<E>(e, null));
size++;
return;
}
public int binarySearchLinkedList(SinglyLinkedList<E> list, E target) {
int left = 0;
int right = list.getSize();
while (left <= right) {
int mid = (left + right) / 2;
Node<E> temp = head;
for (int i = 0; i < mid - 1; i++) {
temp = temp.next;
}
if (temp.getElement() instanceof Number && target instanceof Number) {
if (Integer.parseInt(temp.getElement().toString()) == Integer.parseInt(target.toString())) {
return mid;
} else if (Integer.parseInt(temp.getElement().toString()) > Integer.parseInt(target.toString())) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
public String toString() {
StringBuilder sb = new StringBuilder();
Node<E> temp = head;
while (temp != tail) {
sb.append(temp.getElement()).append(", ");
temp = temp.next;
if (temp == tail) {
sb.append(temp.getElement());
}
}
return sb.toString();
}
}
And the main method;
public static void main(String[] args) {
SinglyLinkedList<Integer> list = new SinglyLinkedList<>();
list.append(10);
list.append(20);
list.append(30);
list.append(40);
list.append(50);
list.append(60);
list.append(70);
list.append(80);
list.append(90);
list.append(100);
System.out.println(list);
System.out.println(list.binarySearchLinkedList(list, 30));
}
It returns;
10, 20, 30, 40, 50, 60, 70, 80, 90, 100
-1
I'm guessing this line is the biggest issue:
for (int i = 0; i < mid - 1; i++) {
Consider what happens if mid is 1. The loop won't execute, because it is not the case that 0 < 1-1. So the inspected node won't be the one you think it is. The actual node at index mid will never be inspected. So the outer loop will eventually exit, never having found the target. Presumably your method ends with return -1;.
Other issues include:
You're initializing right to an exclusive value, but treat it as inclusive elsewhere. Consider using int right = list.getSize() - 1;
You've declared a generic method, but implemented it only for Integer. One way around this would be to limit the generic type to one that supports Comparable - e.g., E extends Comparable<E>.
You're implementing a binary search in a linked list. In a linked list, linear search would be simpler and no less efficient. Or you could use a data structure that supports constant-time access by index, such as an array or ArrayList.

Creating a new instance of a ListNode

The problem I am trying to solve is a LeetCode problem, but I am stuck
https://leetcode.com/problems/add-two-numbers/
I have tried the following
import java.util.*;
class Solution {
private ListNode l = new ListNode(0);
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int pow = 0;
int counter = 0;
int sum1 = 0;
int sum2 = 0;
while(l1 != null && l2 != null)
{
sum1 = sum1 + ((int) (l1.val * (Math.pow(10,pow))));
sum2 = sum2 + ((int) (l2.val * (Math.pow(10,pow))));
pow++;
l1 = l1.next;
l2 = l2.next;
}
pow = pow - 1;
int final_sum = sum1 + sum2;
String number = String.valueOf(final_sum);
char[] digits = number.toCharArray();
l = l.next;
ListNode x = new ListNode();
x.val = (digits[2] - '0');
l= x;
addElement(digits[1] - '0');
addElement(digits[0] - '0');
return l;
}
public void addElement(int number)
{
ListNode x = new ListNode();
x.val = number;
l.next = x;
}
}
However, I noticed that this just replaces the last given value of ListNode x and does not add on to ListNode l. I am first trying to make it work with one instance of a ListNode without creating multiple "ListNode x = new ListNode()" with different variable names.
At the moment it is just returning [7,8] when given [2,4,3] and [5,6,4] when it should be returning [7,0,8]. Any hints or advice would help.
Rey, do not make it complex, this is just an example
start with a null node;
ListNode l3 = null;
define a rem and the temp node;
int rem = 0;
ListNode temp = l3;
iterate the both nodes;
while(l1 != null && l2 != null)
sum the vals,
int sum = l1.val + l2.val;
if temp is null, you are at the beginning;
l3 = temp = new ListNode(sum%10);
rem = sum / 10;
if not, calculate next, carry if rem
sum += rem;
rem = sum / 10;
temp.next = new ListNode(sum%10);
move temp
temp = temp.next;
also move sources,
l1 = l1.next;
l2 = l2.next;
when you finished, carry if rem again,
if (rem > 0) {
temp.next = new ListNode(rem);
}
and return;
return l3;
Solution with the help of recursion
class solution{
int carry =0;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// create a base case where recursion terminates
if (l1 == null && l2 == null && carry == 0) {
return null;
}
// calculate sum of current node and get carry variable updated
int val1 = l1 == null ? 0 : l1.val;
int val2 = l2 == null ? 0 : l2.val;
int sum = val1 + val2 + carry;
carry = sum/10;
// update l1,l2 with next node if occur
l1 = l1 == null ? null : l1.next;
l2 = l2 == null ? null : l2.next;
//perform recursion and store result in new Listnode and.
ListNode ans = new ListNode(sum%10, addTwoNumbers(l1, l2));
return ans;
}

Changing from curr.next to curr gives me nullpointerException. Why?

The entire code was like following:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode curr = dummyHead, p = l1, q = l2;
int carry = 0;
int sum;
while(p != null || q != null){
int x = (p != null)? p.val:0;
int y = (q != null)? q.val:0;
sum = x + y + carry;
carry = sum/10;
curr.next = new ListNode(sum%10); // What if I change it to curr.val = sum%10?
curr = curr.next;
if(p != null) p = p.next;
if(q != null) q = q.next;
}
if(carry > 0){
curr.next = new ListNode(carry);
}
return dummyHead.next; // If the change I made above works, then I just return dummyHead
}
I was just wondering why not just using curr.val = sum%10 instead of curr.next = new ListNode(sum%10)? And then in the end, instead of returning dummyHead.next, we can return dummyHead itself, sounds reasonable right? So I made the change but I got a nullpointerException. Why? How come dummyHead or curr is ever null? So basically what I was trying to do is that in each iteration I work out the sum and then assign it to curr.val, and then curr changes to next, so on and so forth.

How to set an element at Row index and a column index in order to create a sparse matrix using linked list

I want to create a sparse matrix using linked lists in java. A node is sorted based on the row and column index. I managed to create a sparse vector but for some reason, I can't figure out how to do it using two indices.
The constructor
public LLSparseM(int nr, int nc) {
numeberOfColums = nc;
numerOfRows = nr;
head = new node(-1, -1, 0, null, null);
tail = new node(nr, nc, 0, head, null);
head.setNext(tail);
return;
}
The set element method
public void setElement(int ridx, int cidx, int val) {
if (head.getNext().getElement() == 0) {
node newnode = new node(ridx, cidx, val, head, tail);
head.setNext(newnode);
tail.setPrev(newnode);
} else {
node current = head.getNext();
while (current.getRidx() < ridx || (current.getRidx() <= ridx && current.getCidx() < cidx)) {
current = current.getNext();
}
if (current.getRidx() == ridx && current.getCidx() == cidx) {
node newest = new node(ridx, cidx, val, current.getPrev(), current.getNext());
current.getPrev().setNext(newest);
current.getNext().setPrev(newest);
} else if (current.getRidx() > ridx || current.getRidx() >= ridx && current.getCidx() > current.getCidx()) {
if (head.getRidx() > ridx || head.getRidx() == ridx && head.getCidx() > cidx) {
node newest = new node(ridx, cidx, val, null, head);
tail = head;
head.setPrev(newest);
head = newest;
tail.setNext(null);
} else {
node temp = current.getPrev();
node newest = new node(ridx, cidx, val, temp, current);
temp.setNext(newest);
current.setPrev(newest);
}
} else if (current.getRidx() == numerOfRows && current.getCidx() == numeberOfColums) {
node newest = new node(ridx, cidx, val, tail.getPrev(), tail);
tail.getPrev().setNext(newest);
}
}
}

Categories

Resources