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;
}
Related
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;
}
}
}
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;
}
}
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.
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);
}
}
}
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.