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

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.

Related

LinkedList Add Two Numbers: LeetCode

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;
}
}

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;
}

Replacing Node in LinkedList not actually replacing anything

I am currently writing an implementation of a doubly linked list and am having trouble setting a node to a certain value. Since the data in the nodes is final, I need to replace the entire node, but the code that I wrote for that seems to be working until it exits the method and the original list hasn't been changed at all. Is there anything that I'm missing in the code here?
`public void set(int index, String item) {
if (index < 0 || index >= this.size) {
throw new IndexOutOfBoundsException();
}
Node curr = this.front;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
Node temp = new Node(item);
temp.prev = curr.prev;
temp.next = curr.next;
curr = temp;
}`
You should also change "next of the previous node" and "prev of the next node". Assume prev is the previous node of cur and next is the next node of cur.
Node temp = new Node(item);
temp.prev = prev;
temp.next = next;
next.prev = temp;
prev.next = temp;
You should deal with edge problems.
you can
System.out.println(curr.val);
and you find the print is actually the same as item
but when you return ,you will find nothing change
you just need find the pre node of curr and set pre.next= curr(where is changed)
`public void set(int index, String item) {
if (index < 0 || index >= this.size) {
throw new IndexOutOfBoundsException();
}
Node curr = this.front;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
Node temp = new Node(item);
temp.prev = curr.prev;
temp.next = curr.next;
curr = temp;
//here you need to set maybe
// Node tmp=curr.prev;
// tmp.next=curr;
}`

Inserting a Node after a given position in a singly linked list

My code works fine in Eclipse but not in a compiler in a programming site. This code is about adding a node at given position.
Node InsertNth(Node head, int data, int position) {
Node n = new Node();
Node last = head;
int count = 0;
if (position == 0) {
n.data = data;
n.next = head;
head=n;
return n;
}
while (count < position) {
count++;
last = last.next;
}
n.data = data;
n.next = last.next;
last.next = n;
return head;
}
You go too far with the loop, and also don't check the position is in range:
Node InsertNth(Node head, int data, int position) {
Node n = new Node();
n.data = data;
if (position == 0) {
n.next = head;
return n;
}
Node last = head;
for (int count = 0; count < position-1; count++) {
if (last == null) {
return null;
}
last = last.next;
}
n.next = last.next;
last.next = n;
return head;
}
Also, a for loop is more suitable, and some other things could be rearranged better.

does this merge sort use O(1) extra space?

Just for my clarification, constant space means O(1) space, right?
Anyway, here is a code i have written, please tell me if it uses O(1) space.
void mergeSort() {
ListNode merge = this.head;
this.head = mergeSort(merge);
}
ListNode mergeSort(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode slow = head; ListNode fast = head.next;
while(fast!=null && fast.next !=null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode left = head; ListNode right = slow.next;
slow.next = null;
left = mergeSort(left);
right = mergeSort(right);
return merge(left, right);
}
ListNode merge(ListNode L, ListNode R) {
if(L==null) return R;
if(R==null) return L;
ListNode h = null;
if(L.val <= R.val )){
h = L;
h.next = merge(L.next, R);
} else {
h = R;
h.next = merge(L, R.next);
}
return h;
}

Categories

Resources