delete odd numbers in queue - java

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();

Related

How can I reverse the contents of a queue

I want the program to print in the output Reversing the contents of the queue, (use an array hint)
I have 3 classes , Node , class , main
public class QueuePtr {
Node front, rear;
QueuePtr () { rear = front = null; }
Boolean isEmpty ()
{
if (front == null) return true; else return false;
}
void ENQUEUE (int x) {
Node N = new Node(x);
if(rear != null) {rear.next = N;
rear = N; }
else { front = rear = N; }
}
int FRONT (){
if (!isEmpty ()) return front.data;
else {System.out.println(" error queue is empty");
return -1111; }
}
void DEQUEUE (){
if (isEmpty ()) System.out.println(" error queue is empty");
else if (front == rear) front = rear = null;
else front = front.next;
public static void main(String arg[])
{
QueuePtr Q = new QueuePtr () ;
Q.ENQUEUE(10);
Q.ENQUEUE(20);
Q.ENQUEUE(30);
Q.ENQUEUE(40);
Reverse (Q);
}
output
[40,30,20,10]
You can use recursion to print your queue in reverse order as you deconstruct it:
public static void printBackwards(QueuePtr q) {
if (!q.isEmpty()) {
Node r = q.DEQUEUE();
printBackwards(q);
System.out.println(r);
}
}

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)...

LinkedList from scratch, replacing a node

I was given an assignement to create a LinkedList from scratch, I've figured how to code a method that add a node at the end of the list but I still can't figure how to replace a node. Here is what I have so far:
public boolean replace(int element, int index) {
Node temp= new Node(pElement);
Node current = getHead();
if (!isEmpty()) {
for (int i = 0; i < index && current.getNext() != null; i++) {
current = current.getNext();
}
temp.setNext(noeudCourant.getNext());
noeudCourant.setNext(temp);
listCount++;
return true;
}
return false;
}
Using aNode.replace(10, 4) on "0 1 2 3 4 5 6 7 8 9 10"
will make it into
[0]->[1]->[2]->[3]->[4]->[10]->[5]->[6]->[7]->[8]->[9]->[10]
but I want:
[0]->[1]->[2]->[3]->[10]->[5]->[6]->[7]->[8]->[9]->[10]
Any help is appreciated.
[edit]I already have a working method setData() but the assignment I have forbid me to use it. What I want is basically this:
http://i.imgur.com/oOVYCvc.png
Here is a simple solution for your question:
package linkedlist;
class Node {
public Node next = null;
public int element;
public Node(int el) {
element = el;
}
}
class LinkedList {
public Node first = null;
public void add(Node node) {
if (first == null) {
first = node;
} else {
// Traverse to the last
Node cursor = first;
while (cursor.next != null) {
cursor = cursor.next;
}
cursor.next = node;
}
}
public void add(int[] elements) {
int len = elements.length;
for (int i=0;i < len;i++) {
add(new Node(elements[i]));
}
}
public boolean replace(int element, int index) {
Node cursor = first;
Node prev = null;
while (cursor != null && index >= 0) {
index--;
prev = cursor;
cursor = cursor.next;
}
if (index > 0) return false;
if (prev != null)
prev.element = element;
return true;
}
public void displayAll() {
Node cursor = first;
while (cursor != null) {
System.out.print(cursor.element + " ");
cursor = cursor.next;
}
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
// Prepare elements
LinkedList linkedList = new LinkedList();
linkedList.add(new int[]{0,1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
println("Display the initial linked list content:");
linkedList.displayAll();
println("After replace:");
linkedList.replace(10, 4);
linkedList.displayAll();
println("Done");
}
static void println(String msg) {
System.out.println(msg);
}
}
If you really want to replace the Node and do not delete it then here is how you should be writing your replace() function:
public boolean replace(int element, int index) {
Node head = getHead();
int counter = 0;
while(null != head && counter++ < index - 1) {
head = head.getNext();
}
if(null == head || null == head.getNext()) return false;
Node newNode = new Node(element);
newNode.setNext(head.getNext().getNext());
head.setNext(newNode);
return true;
}
Here, I'm assuming that you have setNext() method in your Node class to set the link.
Also note that here it is assumed that you'll never replace head itself i.e. you'll never replace the element at index 0 or else you'll have to return the new head from the function.
Try below code. I have written the logic in comments wherever required.
public boolean replace(int element, int index) {
Node temp= new Node(pElement);
Node current = getHead();
if (!isEmpty()) {
//Run for loop one less than index value.
for (int i = 0; i < index -1 && current.getNext() != null; i++) {
current = current.getNext();
}
// At this point current points to element 3.
// Set next element of node 4 as a next element of new element 10.
temp.setNext(current.getNext().getNext());
// at this point we have two references for element 5 like below
// [0]->[1]->[2]->[3]->[4]->[5]->[6]->[7]->[8]->[9]->[10]
// [10]->[5]->[6]->[7]->[8]->[9]->[10]
// Set null to next element of of element 4 to remove reference to
// element 5
current.getNext().setNext(null);
// At this point we have two list as below:
// [0]->[1]->[2]->[3]
// [10]->[5]->[6]->[7]->[8]->[9]->[10]
// Set new element as next of current element (current element is 3)
current.setNext(temp);
// here we have replaced the element 4 with element 10
listCount++;
return true;
}
return false;
}

How to convert the below recursive functions to for loop iterations

Iterator words = treeSearch.getItems().iterator();
int addCount = 0;
while (words.hasNext())
{
numWords++;
rootNode = add(objectToReference, addCount++, (ITreeSearch) words.next(), 0, rootNode);
}
//Add to the Tree
private TernaryTreeNode add(Object storedObject, int wordNum, ITreeSearch treeSearch, int pos, TernaryTreeNode parentNode) throws NoSearchValueSetException
{
if (parentNode == null)
{
parentNode = new TernaryTreeNode(treeSearch.getNodeValue(pos));
}
if (parentNode.lessThan(treeSearch, pos))
{
parentNode.left = add(storedObject, wordNum, treeSearch, pos, parentNode.left);
}
else if (parentNode.greaterThan(treeSearch, pos))
{
parentNode.right = add(storedObject, wordNum, treeSearch, pos, parentNode.right);
}
else
{
if (pos < treeSearch.getNumberNodeValues())
{
parentNode.mid = add(storedObject, wordNum, treeSearch, pos + 1, parentNode.mid);
}
else
{
numberOfObjectsStored++;
parentNode.addStoredData(storedObject);
}
}
return parentNode;
}
This a snippet of my code in my Ternary Tree which I use for inserting a Name of a person(can hav multiple words in a name, like Michele Adams, Tina Joseph George, etc). I want to convert the above recursion to a for loop / while iterator.
Please guide me on this.
General idea in replacing recursion with iteration is to create a state variable, and update it in the loop by following the same rules that you follow in your recursive program. This means that when you pick a left subtree in the recursive program, you update the state to reference the left subtree; when you go to the right subtree, the state changes to reference the right subtree, and so on.
Here is an example of how to rewrite the classic insertion into binary tree without recursion:
public TreeNode add(TreeNode node, int value) {
// Prepare the node that we will eventually insert
TreeNode insert = new TreeNode();
insert.data = value;
// If the parent is null, insert becomes the new parent
if (node == null) {
return insert;
}
// Use current to traverse the tree to the point of insertion
TreeNode current = node;
// Here, current represents the state
while (true) {
// The conditional below will move the state to the left node
// or to the right node, depending on the current state
if (value < current.data) {
if (current.left == null) {
current.left = insert;
break;
} else {
current = current.left;
}
} else {
if (current.right == null) {
current.right = insert;
break;
} else {
current = current.right;
}
}
}
// This is the original node, not the current state
return node;
}
Demo.
Thanks dasblinkenlight..
This is my logic for replacing the above recursive function for a ternary tree.
Iterator words = treeSearch.getItems().iterator();
while (words.hasNext())
{
for (int i = 0; i < word.getNumberNodeValues(); i++)
{
add_Non_Recursive(objectToReference, word, i);
}
}
//Add to Tree
private void add_Non_Recursive(Object storedObject, ITreeSearch treeSearch, int pos) throws NoSearchValueSetException
{
TernaryTreeNode currentNode = rootNode;
// Start from a node(parentNode). If there is no node, then we create a new node to insert into the tree.
// This could even be the root node.
if (rootNode == null)
{
rootNode = new TernaryTreeNode(treeSearch.getNodeValue(pos));
}
else
{
while (currentNode != null)
{
if (currentNode.lessThan(treeSearch, pos))
{
if (currentNode.left == null)
{
currentNode.left = new TernaryTreeNode(treeSearch.getNodeValue(pos));
currentNode = null;
}
else
{
currentNode = currentNode.left;
}
}
else if (currentNode.greaterThan(treeSearch, pos))
{
if (currentNode.right == null)
{
currentNode.right = new TernaryTreeNode(treeSearch.getNodeValue(pos));
currentNode = null;
}
else
{
currentNode = currentNode.right;
}
}
else
{
if (currentNode.mid == null)
{
currentNode.mid = new TernaryTreeNode(treeSearch.getNodeValue(pos));
currentNode = null;
}
else
{
currentNode = currentNode.mid;
}
}
}
}
}
But I dropped this logic as it wasnt great in performing, it took more time than the recursive counterpart.

deleteBack java program

I am doing some exercises on practice-it website. And there is a problem that I don't understand why I didn't pass
Write a method deleteBack that deletes the last value (the value at the back of the list) and returns the deleted value. If the list is empty, your method should throw a NoSuchElementException.
Assume that you are adding this method to the LinkedIntList class as defined below:
// A LinkedIntList object can be used to store a list of integers.
public class LinkedIntList {
private ListNode front; // node holding first value in list (null if empty)
private String name = "front"; // string to print for front of list
// Constructs an empty list.
public LinkedIntList() {
front = null;
}
// Constructs a list containing the given elements.
// For quick initialization via Practice-It test cases.
public LinkedIntList(int... elements) {
this("front", elements);
}
public LinkedIntList(String name, int... elements) {
this.name = name;
if (elements.length > 0) {
front = new ListNode(elements[0]);
ListNode current = front;
for (int i = 1; i < elements.length; i++) {
current.next = new ListNode(elements[i]);
current = current.next;
}
}
}
// Constructs a list containing the given front node.
// For quick initialization via Practice-It ListNode test cases.
private LinkedIntList(String name, ListNode front) {
this.name = name;
this.front = front;
}
// Appends the given value to the end of the list.
public void add(int value) {
if (front == null) {
front = new ListNode(value, front);
} else {
ListNode current = front;
while (current.next != null) {
current = current.next;
}
current.next = new ListNode(value);
}
}
// Inserts the given value at the given index in the list.
// Precondition: 0 <= index <= size
public void add(int index, int value) {
if (index == 0) {
front = new ListNode(value, front);
} else {
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = new ListNode(value, current.next);
}
}
public boolean equals(Object o) {
if (o instanceof LinkedIntList) {
LinkedIntList other = (LinkedIntList) o;
return toString().equals(other.toString()); // hackish
} else {
return false;
}
}
// Returns the integer at the given index in the list.
// Precondition: 0 <= index < size
public int get(int index) {
ListNode current = front;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current.data;
}
// Removes the value at the given index from the list.
// Precondition: 0 <= index < size
public void remove(int index) {
if (index == 0) {
front = front.next;
} else {
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}
}
// Returns the number of elements in the list.
public int size() {
int count = 0;
ListNode current = front;
while (current != null) {
count++;
current = current.next;
}
return count;
}
// Returns a text representation of the list, giving
// indications as to the nodes and link structure of the list.
// Detects student bugs where the student has inserted a cycle
// into the list.
public String toFormattedString() {
ListNode.clearCycleData();
String result = this.name;
ListNode current = front;
boolean cycle = false;
while (current != null) {
result += " -> [" + current.data + "]";
if (current.cycle) {
result += " (cycle!)";
cycle = true;
break;
}
current = current.__gotoNext();
}
if (!cycle) {
result += " /";
}
return result;
}
// Returns a text representation of the list.
public String toString() {
return toFormattedString();
}
// ListNode is a class for storing a single node of a linked list. This
// node class is for a list of integer values.
// Most of the icky code is related to the task of figuring out
// if the student has accidentally created a cycle by pointing a later part of the list back to an earlier part.
public static class ListNode {
private static final List<ListNode> ALL_NODES = new ArrayList<ListNode>();
public static void clearCycleData() {
for (ListNode node : ALL_NODES) {
node.visited = false;
node.cycle = false;
}
}
public int data; // data stored in this node
public ListNode next; // link to next node in the list
public boolean visited; // has this node been seen yet?
public boolean cycle; // is there a cycle at this node?
// post: constructs a node with data 0 and null link
public ListNode() {
this(0, null);
}
// post: constructs a node with given data and null link
public ListNode(int data) {
this(data, null);
}
// post: constructs a node with given data and given link
public ListNode(int data, ListNode next) {
ALL_NODES.add(this);
this.data = data;
this.next = next;
this.visited = false;
this.cycle = false;
}
public ListNode __gotoNext() {
return __gotoNext(true);
}
public ListNode __gotoNext(boolean checkForCycle) {
if (checkForCycle) {
visited = true;
if (next != null) {
if (next.visited) {
// throw new IllegalStateException("cycle detected in list");
next.cycle = true;
}
next.visited = true;
}
}
return next;
}
}
// YOUR CODE GOES HERE
}
My work so far is this:
public int deleteBack(){
if(front==null){
throw new NoSuchElementException();
}else{
ListNode current = front;
while(current!=null){
current = current.next;
}
int i = current.data;
current = null;
return i;
}
}
Don't you want to iterate until the current.next is != null?
What you have now passes the entire list, and your last statements do nothing, since current is null already.
Think about the logic you have here
while(current!=null){
current = current.next;
}
When that loop exits, current == null, and then you try to access current's data. Does this point you in the right direction?
// This is the quick and dirty
//By Shewan
public int deleteBack(){
if(size()== 0){ throw new NoSuchElementException(); }
if(front==null){ throw new NoSuchElementException();
}else{
if(front.next == null){
int i = front.data;
front = null;
return i;
}
ListNode current = front.next;
ListNode prev= front;
while(current.next!=null){
prev = current;
current = current.next;
}
int i = current.data;
prev.next = null;
return i;
}
}

Categories