Creating a new instance of a ListNode - java

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

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

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 get fibonacci series within range without recursion

I am trying to calculate the fibonacci numbers within specific range(wide range of numbers in thousands)
I have wrote this but for I do not know to to modify it to make it within a range for example i need to get fibonacci numbers between 5027 and 8386589
class Fibonacci
{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i)
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}
int fib(int low, int high){
// Initialize first three Fibonacci Numbers
int n1 = 0, n2 = 1, n3 = 1;
// Count fibonacci numbers in given range
int result = 0;
while (n1 <= high){
if (n1 >= low)
result++;
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
return result;
}
Try using a while loop instead of a for loop and include an if-statement
while(n3<8386589){
if(n3>5027){
System.out.print(n3+" ");
}
n3=n1+n2;
n1=n2;
n2=n3;
}
FWIW, here's my version (also using a while loop):
private static void Fibonacci(long lower, long upper)
{
long curr = 1, prev = 1;
while (curr <= upper)
{
long temp = curr;
curr = prev + curr;
prev = temp;
if (curr >= lower && curr <= upper)
{
System.out.println(curr);
}
}
}
The some idea just using BigInteger for bigger values :
private static BigInteger function_f(int n) {
// if n = 0 => f(n) = 0
if(n == 0)
return new BigInteger("0");
// Initialization of variables
// if n = 1 => f(n) = 1 (case included)
BigInteger result = new BigInteger("1");
BigInteger last_fn = new BigInteger("0");
BigInteger before_last_fn = new BigInteger("0");
// Do the loop for n > 1
for (int i = 2; i <= n; i++) {
// f(n - 2)
before_last_fn = last_fn;
// f(n - 1)
last_fn = result;
// f(n - 1) + f(n - 2)
result = last_fn.add(before_last_fn);
}
// Return the result
return result;
}

How to find the smallest count in my BST

What I'm trying to do right now is find the minimum value of repeat count in my binary search tree (BST).
What this means is that the BST is normal when inserting values, but then when it gets the same value twice it instead will increment the value of repeat count, which the tree isn't dependent on (so I can't just go left for the minimum value).
I have tried getting the minimum value but it always comes up short. The function trying to get the smallest is findSmallest
public static void main(String[] args) {
int x = 0; //random number
Random rnum = new Random();
SBT sbt = new SBT();
for(int i = 0; i < 100; i++){
x = rnum.nextInt(20) + 1;
sbt.insert(x);
}
sbt.printLargestCount();
sbt.printSmallestCount();
sbt.FS();
sbt.deleteBoth();
System.out.println("Sum of the key values is: " + sbt.sumKeyValue());
System.out.println("Sum of the repeat counts is: " + sbt.sumReapeatCount());
sbt.inorder();
}
Here is the function trying to get the value I am right now trying to go through all the node in the tree and comparing them to the current smallest value.
If the nodes repeatCount is smaller that value it will change value and a global node smallestCount.
I have added those globals below.
private BSTNode root;
private BSTNode largestCount;
private BSTNode smallestCount;
private int sumKeyVal;
public void FS(){
findSmallest(root, 0);
System.out.println("data is: " + smallestCount.data + " repeatCount is: " + smallestCount.repeatCount);
}
private void findSmallest(BSTNode r, int val){
if(r == null) return;
if(r == root)val = r.repeatCount;
if(r.repeatCount < val){
val = r.repeatCount;
smallestCount = r;
System.out.println(val);
}
if(r.right == null && r.left == null)
return;
else if(r.left != null)
findSmallest(r.left,val);
else if(r.right != null)
findSmallest(r.right,val);
}
private BSTNode insert(int x, BSTNode t){
if (t == null){
t = new BSTNode(x);
smallestCount = t;
}
else if (x < t.data)
t.left = insert( x, t.left );
else if (x > t.data)
t.right = insert( x, t.right );
else
t.height = max( height( t.left ), height( t.right ) ) + 1;
return t;
}
private int height(BSTNode t ) {
return t == null ? -1 : t.height;
}
// Function to max of left/right node
private int max(int lhs, int rhs) {
return lhs > rhs ? lhs : rhs;
}
Here is the node class used:
public class BSTNode {
BSTNode left, right;
int data;
int height;
int repeatCount;
/* Constructor */
public BSTNode(){
left = null;
right = null;
data = 0;
height = 0;
repeatCount = 0;
}
/* Constructor */
public BSTNode(int n){
left = null;
right = null;
data = n;
height = 0;
repeatCount = 0;
}
}
I figured it out and tested the code seems to work. Below is the block of code changed.
public void FS(){
findSmallest(root, 0);
}
private int findSmallest(BSTNode r, int val){
if(r == null) return val;
if(r == root)val = r.repeatCount;
if(r.repeatCount < val){
val = r.repeatCount;
smallestCount = r;
}
val = findSmallest(r.left,val);
val = findSmallest(r.right,val);
return val;
}
Getting rid of the if else statements and going with a check for null at the begging traversed through the tree and kept the smallest along the way.

Swapping nodes in a singly linked list java

I have been trying to come up with an algorithm to swap 2 nodes (not necesarily right next to each other) in a singly linked list for 2 days but for some reason I cannot do it.
Here is what I have, I am really new to coding and have been really stressed:
I have managed to place a temp node in but can't actually swap the nodes.
public void swap(int i, int j) {
current = head;
current2 = head;
sllNode temp = new sllNode(" ");
sllNode temp2 = new sllNode(" ");
for(int z = 0; i>z; z++)
current=current.next;
for(int q = 0; j>q; q++)
current2 = current2.next;
temp.next = current2.next.next;
current.next = temp;
current.next = current2.next.next;
current2.next = current;
Why exchange nodes, when you can exchange the data?
public void swap(int i, int j) {
sllNode ithNode = head;
for (int z = 0; z < i; z++) {
ithNode = ithNode.next;
}
sllNode jthNode = head;
for (int q = 0; q < j; q++) {
jthNode = jthNode.next;
}
// Swap the data
String data = ithNode.data;
ithNode.data = jthNode.data;
jthNode.data = data;
}
It would make sense to use a method:
public sllNode get(int i) {
sllNode current = head;
while (i > 0) {
current = current.next;
}
return current;
}
By the way:
The convention for class names is a beginning capital: SllNode.
Do not use fields for things like current and current2 where they can be local variables.
Exchanging nodes, the hard way
Here one has to think, so it is best to deal with special cases first, and then only treat i < j.
public void swap(int i, int j) {
if (i >= size() || j >= size()) {
throw new IndexOutOfBoundsException();
}
if (i == j) {
return;
}
if (j < i) {
swap(j, i);
return;
}
// i < j
sllNode ithPredecessor = null;
sllNode ithNode = head;
for (int z = 0; z < i; z++) {
ithPredecessor = ithNode;
ithNode = ithNode.next;
}
sllNode jthPredecessor = ithNode;
sllNode jthNode = ithNode.next;
for (int q = i + 1; q < j; q++) {
jthPredecessor = jthNode;
jthNode = jthNode.next;
}
// Relink both nodes in the list:
// - The jthNode:
if (ithPredecessor == null) {
head = jthNode;
} else {
ithPredecessor.next = jthNode;
}
sllNode jNext = jthNode.next;
//if (ithNode.next == jthNode) {
if (jthPredecessor == ithNode) {
jthNode.next = ithNode;
} else {
jthNode.next = ithNode.next;
}
// - The ithNode:
if (jthPredecessor == ithNode) {
} else {
jthPredecessor.next = ithNode;
}
ithNode.next = jNext;
}
No guarantee that the logic is okay. There are tricks:
//if (ithNode.next == jthNode) {
if (jthPredecessor == ithNode) {
Both conditions test whether i + 1 == j, but testing on a .next and then assigning makes the condition a momentary state. As you see it would have been easier to have one single if (i + 1 == j) { ... } else { ... } and handle both the ithNode and jthNode.
To do this, you need to swap 2 things: the node as next from the previous node, and the next node.
Once you found current and current2 which are the previous nodes of the nodes you want to swap, do this:
Swap the nodes:
sllNode tmp = current.next;
current.next = current2.next;
current2.next = tmp;
Then swap the next:
tmp = current.next.next;
current.next.next = current2.next.next;
current2.next.next = tmp;
// Swapping two elements in a Linked List using Java
import java.util.*;
class SwappingTwoElements {
public static void main(String[] args)
{
LinkedList<Integer> ll = new LinkedList<>();
// Adding elements to Linked List
ll.add(10);
ll.add(11);
ll.add(12);
ll.add(13);
ll.add(14);
ll.add(15);
// Elements to swap
int element1 = 11;
int element2 = 14;
System.out.println("Linked List Before Swapping :-");
for (int i : ll) {
System.out.print(i + " ");
}
// Swapping the elements
swap(ll, element1, element2);
System.out.println();
System.out.println();
System.out.println("Linked List After Swapping :-");
for (int i : ll) {
System.out.print(i + " ");
}
}
// Swap Function
public static void swap(LinkedList<Integer> list,
int ele1, int ele2)
{
// Getting the positions of the elements
int index1 = list.indexOf(ele1);
int index2 = list.indexOf(ele2);
// Returning if the element is not present in the
// LinkedList
if (index1 == -1 || index2 == -1) {
return;
}
// Swapping the elements
list.set(index1, ele2);
list.set(index2, ele1);
}
}
Output
Before Swapping Linked List :-
10 11 12 13 14 15
After Swapping Linked List :-
10 14 12 13 11 15
Time Complexity: O(N), where N is the Linked List length

Categories

Resources