Swap linkedlist nodes - java

I am trying to solve a question asked in a interview to swap two nodes in a linkedlist. I happened to find the solution for the answer posted online.
public static void searchNode(int dataX, int dataY, Node head) {
Node currentDataX = head, prevDataX = null;
while (currentDataX != null && currentDataX.data != dataX) {
prevDataX = currentDataX;
currentDataX = currentDataX.next;
}
Node currentDataY = head, prevDataY = null;
while (currentDataY != null && currentDataY.data != dataY) {
prevDataY = currentDataY;
currentDataY = currentDataY.next;
}
if (prevDataX == null) {
head = currentDataX;
}else {
prevDataX.next = currentDataY;
}
if (prevDataY == null) {
head = currentDataY;
}else {
prevDataY.next = currentDataX;
}
// Swap next pointers
Node temp = currentDataY.next;
currentDataY.next = currentDataX.next;
currentDataX.next = temp;
}
The solution is very clear to me except I don't understand the else cases where prevDataX and prevDataY are null. Why are we doing prevDataX.next = currentDataY, and prevDataX.next = currentDataY when we are executing a swap in the end anyway.

Related

delete odd numbers in queue

i am trying to delete odd numbers in the queue linked list but I am struggling to make function to
delete the odd here my code for better understanding ;
public class queueLinked {
private Node rear;
private Node front;
private int siz;
public boolean isEmpty() {//function return boolean if is empty or not
boolean response = false;
if (siz == 0) {
response = true;
}
return response;
}
public void enqueue(int element) { // inserting the value type of int
Node node = new Node(element);
if (front == null) {
rear = node;
front = node;
} else {
rear.setNext(node);
rear = node;
siz++;
}
}
public queueLinked() {
front = null;
rear = null;
siz = 0;
}
public Node dequeue() { // to remove the a element in the queue
Node response = null;
if (front != null) ;
if (front.getNext() != null) {
response = new Node(front.getData());
front = front.getNext();
siz--;
} else {
response = new Node(front.getData());
front = null;
rear = null;
}
return response;
}
public Node peak() {
Node response = null;
if (!isEmpty()) {
response = new Node(front.getData());
}
return response;
}
public int getSiz() { // to get the size
return siz;
}
public void display() { // display the queue function
System.out.print("\nQueue = ");
if (siz == 0) {
System.out.print("Empty\n");
return;
}
Node ptr = front;
while (ptr != rear.getNext()) {
System.out.print(ptr.getData() + " ");
ptr = ptr.getNext();
}
System.out.println();
}
public void deleteOdd() { // delete odd number in the queue
System.out.print("\nQueue = ");
if (siz == 0) { //make sure if it is empty or not
System.out.print("Empty\n");
return;
}
Node tempe = front;
if (front.getData() % 2 != 0){
enqueue(front.getData());
front = front.getNext();
rear = rear.getNext();
}
}
}
in function deleteOdd() i tried to make sure if is it empty and then I tried more than way to get the right one if the first one is odd delete it and front = front.next and I do not know if it is right
First, there are some issues in other methods in your code:
Issues
enqueue should also increase the size of the list when adding to an empty list.
dequeue should also decrease the size of the list when removing the last node from it.
dequeue has a wrong semi-colon after if (front != null) ; and so you can get a null pointer exception on the line below it.
Here is a possible correction with minimal changes:
public void enqueue(int element) {
Node node = new Node(element);
if (front == null) {
rear = node;
front = node;
} else {
rear.setNext(node);
rear = node;
}
siz++; // size should be updated in both cases
}
public Node dequeue() {
Node response = null;
if (front != null) { // correction of misplaced semi-colon
response = new Node(front.getData());
front = front.getNext();
if (front == null) {
rear = null;
}
siz--; // size should be updated in both cases
}
return response;
}
deleteOdd
I chose to only use public methods of the class, so that this function can be easily coded outside of the class, if desired.
The current size of the queue is used for a count down, so every node is visited exactly once. The nodes with even data are appended to the queue again, but this count down will prevent us from visiting those again (and again, ...):
public void deleteOdd() {
for (int count = getSiz(); count > 0; count--) {
Node node = dequeue();
if (node.getData() % 2 == 0) {
enqueue(node.getData());
}
}
}
Try the following function to delete odd number in queue.
public void deleteOdd() { // delete odd number in the queue
if (size == 0) { // make sure if it is empty or not
System.out.print("Empty\n");
return;
}
Node ptr = front;
while (ptr != rear.getNext()) {
if (ptr.getData() % 2 != 0) {
Node tmp = ptr.getNext();
ptr.data = tmp.getData();
ptr.next = tmp.next;
size--;
}
else
ptr = ptr.getNext();
}
System.out.println();
}
QueueLinked queue = new QueueLinked();
for (int i=1; i<=20; i++) {
queue.enqueue(i);
}
queue.display();
queue.deleteOdd();

Issue sorting LinkedList with Item object

I have an issue creating a sort() method for my linked list.
This is my implementation of Comparable in the Item class.
public class Item implements Comparable <Item>{
public Date delivered;
public final String RFIDNR;
public String name;
}
public int compareTo(Item other)
{
return name.compareTo(other.getItemName());
}
This is my sort method in my linked list class
public void sort()
{
Node node = header.next;
Node tempNode = null;
boolean sorted = false;
while (!sorted)
{
sorted = true;
while (node != null)
{
if (node.itm.compareTo(node.next.itm) > 0) throw new NullPointerException();
{
tempNode = node.next;
node.next = node;
node = tempNode;
sorted = false;
}
node = node.next;
}
}
}
What i try to do here is change position of elements that are not in ascending order and switch them. Going through the whole list until sorted = true.
I am running into NullPointerException errors.
Any help is much appreciated.
Look at the following code.
while (node != null) {
if (node.itm.compareTo(node.next.itm) > 0) throw new
NullPointerException();
{
You don't check to see if node.next is null so you try to compare to something that isn't there when trying to access node.next.itm.
I can't guarantee a specific solution since you didn't post your implementation but you need to also ensure node.next is not null. Try the following:
while (node != null) {
if (mode.next != null && node.itm.compareTo(node.next.itm) > 0) {
//do the swapping
}
Solved it using the following.
for (int i = 0; i < size; i++)
{
Node node = header.next;
Item temp = null;
while (node.next != null) {
if (node.itm.compareTo(node.next.itm) > 0)
{
temp = node.next.itm;
node.next.itm = node.itm;
node.itm = temp;
}
node = node.next;
}
}

Why does my method fail to sort my linked list alphabetically?

public class doubleLinkedList {
class Node {
String value;
Node prev;
Node next;
Node(String val, Node p, Node n) {
value = val;
prev = p;
next = n;
}
Node(String val) {
value = val;
prev = null;
next = null;
}
}
Node first;
Node last;
public doubleLinkedList() {
first = null;
last = null;
}
public boolean isEmpty() {
if (first == null)
return true;
else
return false;
}
/**The size method returns the length of the linked list
* #return the number of element in the linked list
*/
public int size() {
int count = 0;
Node traverse = first;
while (traverse != null) {
count++;
traverse = traverse.next;
}
return count;
}
public void add(String element) {
if (isEmpty()) {
first = new Node(element);
last = first;
} else {
Node p = first;
Node elementTobeAdded;
while (((p.value).compareTo(element)) > 0 && p.next != null) {
p = p.next;
}
if (p.next != null) {
elementTobeAdded = new Node(element, p, p.next);
p.next.prev = elementTobeAdded;
p = elementTobeAdded.prev;
} else {
elementTobeAdded = new Node(element, p, null);
p.next = elementTobeAdded;
elementTobeAdded.next = null;
last = elementTobeAdded;
}
}
}
public void printForward() {
Node printNode = first;
while (printNode != null) {
System.out.print(printNode.value + ", ");
printNode = printNode.next;
}
}
}
public class test {
public static void main(String[] args) {
doubleLinkedList car = new doubleLinkedList();
car.add("Jeep");
car.add("benz");
car.add("Honda");
car.add("Lexus");
car.add("BMW");
car.printForward();
}
}
My add method is trying to add nodes to a list in alphabetical order. My printForward method prints out each element in the list.
In my main method, it prints out "Jeep, benz, Honda, BMW,", which is not in alphabetical order.
Change the not empty case for your add method from this
Node p = first;
Node elementTobeAdded;
while(((p.value).compareTo(element)) > 0 && p.next != null)
{
p = p.next;
}
if(p.next != null)
{
elementTobeAdded = new Node(element,p,p.next);
p.next.prev = elementTobeAdded;
p = elementTobeAdded.prev;
}
else
{
elementTobeAdded = new Node(element, p, null);
p.next = elementTobeAdded;
elementTobeAdded.next = null;
last = elementTobeAdded;
}
to this:
Node p = first;
while (p.value.compareTo(element) < 0 && p.next != null) {
p = p.next;
}
if (p.value.compareTo(element) > 0) {
Node toAdd = new Node(element, p.prev, p);
p.prev = toAdd;
if (toAdd.prev != null) {
toAdd.prev.next = toAdd;
}else {
first = toAdd;
}
}else {
Node toAdd = new Node(element, p, p.next);
p.next = toAdd;
if (toAdd.next != null) {
toAdd.next.prev = toAdd;
}else {
last = toAdd;
}
}
There were many errors here. The biggest one was that you never checked for the case where the new element should be inserted at the beginning of the list. A new element was always inserted after the first element even if it should have come first.
Note that "benz" comes at the end because the String.compareTo method treats capitals as coming before lower case letters.
It is not an a linked list... You wrote some sort of Queue (with optional possibility to make it Dequeue).
About your question - you have an error in your 'add' method - at least you don't check if it is necessary to move head forward. It is possible that you have another bugs, but it is too hard to read such styled sources (please fix your question formatting)...

Find least common ancestor of two nodes in java

I have looked at a lot of other answers on stackoverflow and can't find anything that works, I either get the root, or node1 itself returned, I'm not sure how to do this recursively and have tried it many times all ending the same way. Any help would be greatly appreciated!
Here's my code:
private static Node findLCA(Node node1, Node node2) {
Node temp1 = node1, temp2 = node2, currentLargest = null;
int largestDepth = 0;
boolean found = false;
if(node1 == null || node2 == null){
return null;
} else{
while(found == false){
if(temp1.getParent() != null && temp2.getParent() != null && temp1.getParent() == temp2.getParent() && nodeDepth(temp1.getParent()) > largestDepth){
largestDepth = nodeDepth(temp1.getParent());
currentLargest = temp1;
temp1 = temp1.getParent();
temp2 = temp2.getParent();
} else if(temp1.getParent() != null){
temp1 = temp1.getParent();
} else if(temp2.getParent() != null){
temp2 = temp2.getParent();
}
if(temp1.getParent() == null && temp2.getParent() == null){
found = true;
}
}
if(nodeDepth(temp1) >= largestDepth){
return temp1;
} else{
return currentLargest;
}
}
}
I edited it to make a list of ancestors of each node, but I'm not sure how to go around checking each one to see if the elements in the list's match up since they are usually different sizes.
Heres the new code:
ArrayList<PhyloTreeNode> list1 = new ArrayList<PhyloTreeNode>();
ArrayList<PhyloTreeNode> list2 = new ArrayList<PhyloTreeNode>();
if(node1 == null || node2 == null){
return null;
} else{
if(node1.getParent() != null){
list1.add(node1.getParent());
findLeastCommonAncestor(node1.getParent(), node2);
}
if(node2.getParent() != null){
list2.add(node2.getParent());
findLeastCommonAncestor(node1, node2.getParent());
}
}
We can use recursive post order traversal for computing lowest common ancestor,
Here is my Java implementation
Here a & b are given input data for which i have to find lowest common ancestors.
public static int lowestcommanancestors(Node root,int a,int b){
if(root==null)
return 0;
int x=lowestcommanancestors(root.left,a,b);
int y=lowestcommanancestors(root.right,a,b);
if(x+y==2){
System.out.println(root.getData());
return 0;
}
if(root.getData()==a || root.getData()==b){
return x+y+1;
}
else{
return x+y;
}
}
First i am checking whether given input node presenting in left subtree or not,if yes just return 1 else 0,Similarly for right sub tree.When sum becomes 2 first time that node will be lowest common ancestors.
Tell me if i am wrong or you are getting difficulties to understanding the code

implementing binary search tree insert

I'm trying to write code for a binary search tree, the first method I'm working on is the add (insert) method. The root seems to insert properly, but I'm getting null pointer exception when adding the second node. I'll indicate the exact problem spot in my code with comments.
If you can see how to fix the bugs, or let me know if my overall logic is flawed it would be incredibly helpful.-- I will mention that this is for school, so I'm not looking to make a really impressive model...most of my layout choices simply reflect the way we've been working in class. Also, method names were selected by the teacher and should stay the same. Feel free to edit the formatting, had a little trouble.
BINARY TREE CLASS
public class BinarySearchTree
{
private static Node root;
public BinarySearchTree()
{
root = null;
}
public static void Add (Node newNode)
{
Node k = root;
if (root == null)//-----------------IF TREE IS EMPTY -----------------
{
root = newNode;
}
else // -------TREE IS NOT EMPTY --------
{
if (newNode.value > k.value) //-------NEW NODE IS LARGER THAN ROOT---------
{
boolean searching = true;
while(searching) // SEARCH UNTIL K HAS A LARGER VALUE
{ //***CODE FAILS HERE****
if(k.value > newNode.value || k == null)
{
searching = false;
}
else {k = k.rightChild; }
}
if ( k == null) { k = newNode;}
else if (k.leftChild == null){ k.leftChild = newNode;}
else
{
Node temp = k.leftChild;
k.leftChild = newNode;
newNode = k.leftChild;
if(temp.value > newNode.value )
{
newNode.rightChild = temp;
}
else
{
newNode.leftChild = temp;
}
}
}
if (newNode.value < k.value) //-----IF NEW NODE IS SMALLER THAN ROOT---
{
boolean searching = true;
while(searching) // ----SEARCH UNTIL K HAS SMALLER VALUE
{// **** CODE WILL PROBABLY FAIL HERE TOO ***
if(k.value < newNode.value || k == null) {searching = false;}
else {k = k.leftChild;}
}
if ( k == null) { k = newNode;}
else if (k.rightChild == null){ k.rightChild = newNode;}
else
{
Node temp = k.rightChild;
k.rightChild = newNode;
newNode = k.rightChild;
if(temp.value > newNode.value )
{
newNode.rightChild = temp;
}
else
{
newNode.leftChild = temp;
}
}
}
}} // sorry having formatting issues
}
NODE CLASS
public class Node
{
int value;
Node leftChild;
Node rightChild;
public Node (int VALUE)
{
value = VALUE;
}
}
TEST APPLICATION
public class TestIT
{
public static void main(String[] args)
{
BinarySearchTree tree1 = new BinarySearchTree();
Node five = new Node(5);
Node six = new Node(6);
tree1.Add(five);
tree1.Add(six);
System.out.println("five value: " + five.value);
System.out.println("five right: " + five.rightChild.value);
}
}
The conditional statement is checked from left to right, so you need to check whether k is null before you check whether k.value > newNode.value because if k is null, then it doesn't have a value.

Categories