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;
}
}
}
Related
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.
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;
}
}
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
I've been stuck on this problem for quite a while. When I run it against my test for relocating index 1, I get from [A][B][C][D][E] to [B][B][C][D][E]. Any help would be much appreciated.
public void moveToTop(int index) throws IllegalArgumentException {
if (index > size) {
throw new IllegalArgumentException();
}
if (index == 0) {
return;
} else {
Node ref = first;
for (int i = 1; i < index; i++) {
ref = ref.next;
}
Node temp = null;
temp = ref.next;
ref = temp.next;
temp = first;
first = temp;
}
}
void moveToTop(int index) {
// index should go until size - 1, not size
if (index >= size) throw new IllegalArgumentException();
// index == 0 should return the list unmodified
if (index == 0) return;
// We start in the head
// first = A -> B -> C -> D -> E
// ref = A -> B -> C -> D -> E
Node ref = first;
for (int i = 0; i < index - 1; i++) {
// And loop until we find the node before the one we want to move
// For index = 1, we won't loop, so ref is still equal to first
ref = ref.next;
}
// temp = A.next => temp = B
Node temp = ref.next;
// ref (A) is the node before the one we wish to move
// A.next = B.next => A.next = C => ref = A -> C -> D -> E
ref.next = temp.next;
// B.next = A => temp = B -> A -> C -> D -> E
temp.next = first;
// first = B -> A -> C -> D -> E
first = temp;
}
Firstly, set the index in the loop to 0.
With what you have there, its content won't be executed.
Secondly, look very closely at the assignment logic that follows. You need to assign the ref node to the temp variable, the ref to the first node, and then the temp to the ref.
Try to use this for loop instead:
for (int i = 0; i <= index; i++) {
ref = ref.next;
}
I am working on an assignment where I have to sort an array and store the indices in a doubly linked list ADT that I have built.
Example:
{"A","B","C","A"} -> {0,3,1,2}
My current approach is to bring the indices into my ADT and then sort the ADT as I sort the array. As far as I can tell, I am doing the exact same operation on both the array and the doubly linked list every time either loop executes, but my output does not match up.
public static void main(String[] args ) {
List A = new List();
String[] inputArray = {"A","C","B","A"};
int i,j;
String key;
//load indices into doubly-linked list
for (int x = 0; x < inputArray.length; x++ ) {
A.append(x);
}
//begin insertion sort
for (j = 1; j < inputArray.length; j++) {
System.out.println(A);
System.out.println(Arrays.toString(inputArray));
key = inputArray[j];
i = j - 1;
while (i >= 0) {
if (key.compareTo(inputArray[i]) > 0) {
break;
}
inputArray[i+1] = inputArray[i];
//moveTo moves the cursor to <int>
A.moveTo(i);
//make sure we aren't trying to insert before first node
if (i > 0) { A.insertBefore(i+1); }
else { A.prepend(i+1); }
//remove node at cursor
A.delete();
i--;
}
inputArray[i+1] = key;
A.moveTo(i+1);
if (i > 0) { A.insertBefore(i+1); }
else { A.prepend(i+1); }
A.delete();
}
System.out.println(A);
System.out.println(Arrays.toString(inputArray));
}
The above code gives the following output:
run:
0 1 2 3
[A, C, B, A]
1 0 2 3
[A, C, B, A]
1 1 2 3
[A, B, C, A]
0 2 3 3
[A, A, B, C]
BUILD SUCCESSFUL (total time: 0 seconds)
EDIT: List.java
public class List {
private class Node{
//Fields
int data;
Node next, previous;
//Constructor
Node(int data) {
this.data = data;
next = null;
previous = null;
}
public String toString() { return String.valueOf(data); }
}
//Fields
private Node frontNode, backNode, cursorNode;
private int totalSize, cursorPosition;
//Constructor
List() {
frontNode = backNode = cursorNode = null;
totalSize = 0;
cursorPosition = -1;
}
//moveTo(int i): If 0<=i<=length()-1, moves the cursor to the element
// at index i, otherwise the cursor becomes undefined.
void moveTo(int i) {
if (i == 0) {
cursorPosition = i;
cursorNode = frontNode;
}
else if (i == length() - 1) {
cursorPosition = i;
cursorNode = backNode;
}
else if (i > 0 && i < length() - 1 ) {
cursorNode = frontNode;
cursorPosition = i;
for (int x=0; x < i; x++) {
cursorNode = cursorNode.next;
}
}
else {
cursorPosition = -1;
}
}
//prepend(int data): Inserts new element before front element in this List.
void prepend(int data) {
Node node = new Node(data);
if ( this.length() == 0 ) {
frontNode = backNode = node;
}
else {
frontNode.previous = node;
node.next = frontNode;
frontNode = node;
}
totalSize++;
//cursorPosition might change?
}
//insertBefore(int data): Inserts new element before cursor element in this
// List. Pre: length()>0, getIndex()>=0
void insertBefore(int data) {
Node node = new Node(data);
if ( this.length() > 0 && this.getIndex() >= 0 ) {
node.previous = cursorNode.previous;
node.next = cursorNode;
cursorNode.previous.next = node;
cursorNode.previous = node;
totalSize++;
}
else if ( this.length() <= 0 )
{
throw new RuntimeException
("Error: insertBefore called on empty list");
}
else {
throw new RuntimeException
("Error: insertBefore called without cursor set");
}
}
OK, thanks. I didn't know exactly what insertBefore() and prepend() were intended to do (I could have guessed, but programming should not be about guessing what methods are supposed to do; seeing the documentation is much better).
Since this is an assignment, I'm not going to give you the answer. But the clue is this: After the first pass through the loop, the dump of A gives you the same indices you started with, but rearranged. I think that's the way it's supposed to be after every loop iteration. But that's not true after the second pass through the loop (1 shows up twice, and 0 is gone). Think about it. When you called A.insertBefore() to rearrange the elements of A, what data should you have told insertBefore() to insert, and what did you actually insert?