I'm new to programming and trying to implement an algorithm which reverse K elements in a queue using linkedlist and stack but for some reason, I'm not able to execute the algorithm, any help is greatly appreciated.
I found queue is coming as empty eventhough I add values to it & I see added values in console but when I checked queue.isEmpty() is coming as true.
Here is my code
public class QueueReverseK {
public void reverse(QueueADT queue, int k) {
if (queue.isEmpty()) {
System.out.println("in if empty");
return;
}
if (k > queue.size()) {
k = queue.size;
} else if (k < 0) {
k = 0;
}
StackADT tempStack = new StackADT(k);
QueueADT newQueue = new QueueADT();
for (int i = 0; i < k; i++) {
tempStack.push(queue.deQueue().getData());
}
while (!tempStack.isEmpty()) {
newQueue.enQueue(tempStack.pop());
}
while (!queue.isEmpty()) {
newQueue.enQueue(queue.deQueue().getData());
}
queue = newQueue;
}
Queue class
public class Queue {
LinkedList items;
int size;
Node head;
Node tail;
LinkedListADT list = new LinkedListADT();
public Queue() {
items = new LinkedList();
size = 0;
head = null;
tail = null;
}
public int size() {
return size;
}
public boolean isEmpty() {
if (head == null) return true;
else return false;
}
public void enQueue(int i) {
items.addHead(i);
}
public Node deQueue() {
return items.deleteHead();
}
public void printQueue() {
items.printList();
}
}
LinkedList Class
public class LinkedList {
Node head;
Node tail;
LinkedList() {
head = null;
tail = null;
}
public void addHead(int val) {
Node n = new Node(val);
if (head == null) {
head = n;
tail = n;
} else {
Node tempNode = head;
while (tempNode.next != null) {
tempNode = tempNode.next;
}
tempNode.next = n;
}
}
public void addTail(int val) {
Node n = new Node(val);
if (head == null) {
head = n;
tail = n;
} else {
tail.next = n;
tail = n;
}
}
public int deleteTail() {
Node n = tail;
if (head == null) {
return -1;
} else if (head == tail) {
head = null;
tail = null;
} else {
Node cur = head;
while (cur.getNext() != tail)
cur = cur.next;
tail = cur;
tail.next = null;
}
return n.getData();
}
public Node deleteHead() {
Node n = head;
head = head.next;
return n;
}
public int count() {
int size = 0;
Node n = head;
while (n != null) {
n = n.getNext();
size++;
}
return size;
}
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
public Node getTail() {
return tail;
}
public void setTail(Node tail) {
this.tail = tail;
}
public void printList() {
if (this.head == null) {
return;
}
// print all nodes
Node tempNode = this.head;
while (tempNode != null) {
System.out.print(tempNode.data + "->");
tempNode = tempNode.next;
}
}
void printMiddle(int n) {
Node slow_ptr = head;
Node fast_ptr = head;
if (head != null) {
while (fast_ptr != null && fast_ptr.next != null) {
fast_ptr = fast_ptr.next.next;
slow_ptr = slow_ptr.next;
}
System.out.print(slow_ptr.data + " ");
for (int i = 1; i <= n && slow_ptr != null; i++) {
slow_ptr = slow_ptr.next;
System.out.print(slow_ptr.data + " ");
}
}
}
}
Main Class
public static void main(String[] args) {
Queue Q = new Queue();
Q.enQueue(1);
Q.enQueue(2);
Q.enQueue(3);
Q.enQueue(4);
QueueReverseK k = new QueueReverseK();
k.reverse(Q, 2)
Q.printQueue();
}
Stack Class
public class Stack {
private int top;
private int items[];
private int max;
public StackADT(int n) {
this.max = n;
top = 0;
items = new int[n];
}
public boolean isEmpty() {
return top == 0;
}
public boolean isFull() {
return top == max;
}
public void push(int item) {
if (isFull()) throw new IllegalArgumentException();
else items[top++] = item;
}
public int pop() {
if (isEmpty()) throw new IllegalArgumentException();
else return items[--top];
}
public int size() {
return top;
}
}
}
Example
input Queue: 12 34 65 76 23 12 36 90
output Queue : 12 34 65 76 90 36 12 23
I'm not entirely positive, but it looks like your queue is acting like a stack. You're enQueue is pushing to the head, not the tail of the queue.
Related
Can someone help me with the interval search in binary tree.
I understand how to check left side of the tree,but I have troubles with chicking right side of it.
This is my code by now.
private boolean search(BSTNode r, int from,int till){
boolean found = false;
int arr[];
arr=new int[10];
int i=0;
while (r != null)
{
int rval = r.getData();
if (from < rval && till >rval) {
r = r.getLeft();
arr[i]=rval;
i++;
}else
r=r.getRight();
}
return found;
}
This is full class of BSTNode.
From and till it is range of interval(from
class BSTNode
{
BSTNode left, right;
int data;
/* Constructor */
public BSTNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BSTNode(int n)
{
left = null;
right = null;
data = n;
}
/* Function to set left node */
public void setLeft(BSTNode n)
{
left = n;
}
/* Function to set right node */
public void setRight(BSTNode n)
{
right = n;
}
/* Function to get left node */
public BSTNode getLeft()
{
return left;
}
/* Function to get right node */
public BSTNode getRight()
{
return right;
}
You can search by using queue like this:
public boolean search(Integer from, Integer till) {
return search(root, from, till);
}
private boolean search(BSTNode root, Integer from, Integer till) {
boolean found = false;
Queue<BSTNode> queue = new ArrayDeque<>();
queue.add(root);
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
BSTNode node = queue.poll();
int data = node.getData();
if (from < data && till > data) {
found = true;
list.add(data);
}
if (node.getLeft() != null)
queue.add(node.getLeft());
if (node.getRight() != null)
queue.add(node.getRight());
}
System.out.println(list);
return found;
}
, full code
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
// Tree building...
tree.insert(50);
tree.insert(40);
tree.insert(20);
tree.insert(10);
tree.insert(50);
System.out.println(tree.search(10, 30));
}
static class BinarySearchTree {
private BSTNode root;
public void insert(Integer item) {
root = insert(root, item);
}
private BSTNode insert(BSTNode node, Integer item) {
if (node == null) {
return new BSTNode(item);
} else if (item.compareTo(node.data) == 0) {
return node;
} else if (item.compareTo(node.data) < 0) {
node.setRight(insert(node.r, item));
return node;
} else {
node.setLeft(insert(node.l, item));
return node;
}
}
public Integer find(Integer target) {
return find(root, target);
}
private Integer find(BSTNode node, Integer target) {
if (node == null) {
return null;
}
Integer cmd = target.compareTo(node.data);
if (cmd == 0) {
return node.data;
} else if (cmd < 0) {
return find(node.getRight(), target);
} else {
return find(node.getLeft(), target);
}
}
public boolean search(Integer from, Integer till) {
return search(root, from, till);
}
private boolean search(BSTNode root, Integer from, Integer till) {
boolean found = false;
Queue<BSTNode> queue = new ArrayDeque<>();
queue.add(root);
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
BSTNode node = queue.poll();
int data = node.getData();
if (from < data && till > data) {
found = true;
list.add(data);
}
if (node.getLeft() != null)
queue.add(node.getLeft());
if (node.getRight() != null)
queue.add(node.getRight());
}
System.out.println(list);
return found;
}
}
static class BSTNode {
Integer data;
BSTNode l = null;
BSTNode r = null;
public BSTNode(Integer data) {
super();
this.data = data;
}
public Integer getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public BSTNode getLeft() {
return l;
}
public void setLeft(BSTNode l) {
this.l = l;
}
public BSTNode getRight() {
return r;
}
public void setRight(BSTNode r) {
this.r = r;
}
#Override
public String toString() {
return "BSTNode [data=" + data + ", l=" + l + ", r=" + r + "]";
}
}
, the output
[20]
true
Trying to implement a SET interface and to use an Iterator for the union method. Inside the union method it never enters the while loop. It does not add the elements from the parameter "set" that the union method has.
Any ideas? :)
package linkedSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import linkedList.LinearNode;
public class LinkedSet implements SetADT {
private int size;
private LinearNode<T> front;
private boolean allowNullElement = false;
// /////////////////////////////////////////////////////
private class LinkedSetIterator implements Iterator<T> {
private LinearNode<T> currentNode;
public LinkedSetIterator() {
currentNode = front;
}
#Override
public boolean hasNext() {
return currentNode == null;
}
#Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T temp = currentNode.getElement();
currentNode = currentNode.getNext();
return temp;
}
}
///////////////////////////////////////////////////
#Override
public Iterator<T> iterator() {
return new LinkedSetIterator();
}
public LinkedSet(boolean allowNullElement) {
size = 0;
front = new LinearNode<T>();
this.allowNullElement = allowNullElement;
}
public String toString() {
String str = "{";
for (int i = 0; i < size; i++) {
str += getNode(i).getElement();
if (i < size - 1) {
str += (", ");
}
}
return str + "}";
}
private LinearNode<T> getNode(int index) {
LinearNode<T> current = front;
for (int i = 0; i < index; i++) {
current = current.getNext();
}
return current;
}
#Override
public void add(T element) {
if (element == null && !allowNullElement) {
throw new IllegalArgumentException(
"Null element is not allowed to add");
}
front = new LinearNode<T>(element, front);
size++;
}
#Override
public T remove(T element) {
if (!(contains(element))) {
throw new IllegalStateException();
}
T temp = null;
;
for (int i = 0; i < size; i++) {
temp = getNode(i).getElement();
if (temp.equals(element) || temp == element) {
if (i == 0) {
front = front.getNext();
break;
} else {
getNode(i).setElement(front.getElement());
front = front.getNext();
break;
}
}
}
size--;
return temp;
}
#Override
public boolean contains(T element) {
for (int i = 0; i < size; i++) {
if (getNode(i).getElement() != null
&& getNode(i).getElement().equals(element)) {
return true;
}
if (getNode(i).getElement() == null
&& getNode(i).getElement() == element) {
return true;
}
}
return false;
}
#Override
public boolean isEmpty() {
return size == 0;
}
#Override
public int size() {
return size;
}
#Override
public boolean isSubset(SetADT<T> set) {
if (set == null) {
throw new IllegalArgumentException();
}
for (int i = 0; i < size; i++) {
T temp = getNode(i).getElement();
if (!(set.contains(temp))) {
return false;
}
}
return true;
}
#Override
public SetADT<T> intersection(SetADT<T> set) {
if (set == null) {
throw new IllegalArgumentException();
}
LinkedSet<T> temp = new LinkedSet<T>(allowNullElement);
for (int i = 0; i < size; i++) {
if (set.contains(getNode(i).getElement())) {
temp.add(getNode(i).getElement());
}
}
return temp;
}
public SetADT<T> union(SetADT<T> set) {
if (set == null) {
throw new IllegalArgumentException();
}
LinkedSet<T> temp = new LinkedSet<T>(allowNullElement);
LinearNode<T> node = front;
for (int i = 0; i < size; i++) {
T el = node.getElement();
temp.add(el);
node = node.getNext();
}
Iterator<T> iterator = set.iterator();
while (iterator.hasNext()) {
temp.add(iterator.next());
}
return temp;
}
}
The LinkedSetIterator.hasNext() method will return false if the set is nonempty. This could be corrected with inverting the condition:
#Override
public boolean hasNext() {
return currentNode != null;
}
I have a to create a double ended queue which can add,remove and peek elements from both sides (i.e, front and rear)
I got the methods for the adding,removing and peeking the elements at the 'head' but i am unable to figure out the methods to do the same thing to the 'tail' of the queue
Here is my code so far:-
public class dequeue
{
private Node rear;
private Node front;
private int counter;
class Node
{
private String item;
private Node link;
}
public Node()
{
rear = front = null;
counter = 0;
}
public void hAdd(String o)
{
Node temp = new Node();
temp.item =o;
temp.link =null;
if (rear==null)
front = rear = temp;
else
{
rear.link = temp;
rear = temp;
}
counter++;
}
public boolean isEmpty()
{
if(counter==0)
return true;
return false;
}
public Object hPeek()
{
return rear.item;
}
public Object hRemove()
{
if (isEmpty())
return null;
else
{
Object temp=front.item;
front = front.link;
if (front == null)
rear = null;
counter--;
return temp;
}
}
public int size()
{
return counter;
}
public void tAdd(String o)
{
Node temp = new Node();
temp.item =o;
temp.link =null;
if (front==null)
front=rear=temp;
else
{
front.link=temp;
front=temp;
}
counter++;
}
public Object tPeek()
{
return front.item;
}
public Object tRemove()
{
if (isEmpty())
return null;
else
{
Object temp=rear.item;
rear=rear.link;
if (rear==null)
front=null;
counter--;
return temp;
}
}
public String toString()
{
StringBuilder result=new StringBuilder();
Node curr=front;
while(curr!=null)
{
result.append(curr.item+" \n");
curr = curr.link;
}
return result.toString();
}
}
public class Dequeue {
int arr[];
int front;
int rear;
int size;
public Dequeue(int size){
this.front = -1;
this.rear=0;
this.size = size;
arr = new int[size];
}
public Dequeue(){
this.front = -1;
this.rear=0;
this.size = 10;
arr= new int[size];
}
boolean isQueueEmpty(){
return (front == -1);
}
boolean isQueueFull(){
return front == ((rear+1)%size);
}
int getFront(){
if(isQueueEmpty()){
return -1;
}
return arr[front];
}
int getRear(){
if(isQueueEmpty() || rear < 0){
return -1;
}
return arr[rear];
}
void insertFront(int data){
if(isQueueFull()){
System.out.println(-1);
return;
}
if(front == -1){
front = 0;
rear=0;
}
else if(front == 0){
front = size - 1 ;
}else{
front = front-1;
}
arr[front] = data;
}
void insertRear(int data){
if(isQueueFull()){
System.out.println(-1);
return;
}
if(front == -1){
front =0;
rear=0;
}
else{
rear =((rear+1)%size);
}
arr[rear] = data ;
}
void deleteFront(){
if(isQueueEmpty()){
System.out.println("-1");
return;
}
if(front == rear){
front = -1;
rear = -1;
}else{
front = ((front+1)%size);
}
}
void deleteRear(){
if(isQueueEmpty()){
System.out.println("-1");
return;
}
if(front == rear){
front =-1;
rear=-1;
}
else if(rear == 0)
rear = size-1;
else
rear = rear-1;
} }
I was given this code to write multiple classes with, but i am having a hard time understand this LinkList. When calling my clear() and my count(E o) method(which are two that is required to write) I am not sure how to run the loop. I am not sure what is referenced has my .length of the array I would call in my class, and keep getting nullpointers. Is size the right variable or should it be something else? Also a bit confused on who to call count(E o) in the main method.
public class GenericLinkedList<E> implements List<E> {
private class Node<E>{
private E data;
private Node<E> next;
}
private E data;
private Node<E> head = null;
private int size = 0;
private Node<E> nodeAt(int index){
Node<E> curNode = head;
int curIndex = 0;
while(curIndex < index){
curNode = curNode.next;
curIndex++;
}
return curNode;
}
#Override
public E get(int index) {
return nodeAt(index).data;
}
#Override
public void add(E value) {
Node<E> node = new Node<E>();
node.data = value;
if(size == 0){
head = node;
}else{
Node<E> curNode = nodeAt(size - 1);
curNode.next = node;
}
size++;
}
public void add(int index, E value){
Node<E> node = new Node<E>();
node.data = value;
if(size == 0){
head = node;
}else if(index == 0){
node.next = head;
head = node;
}else{
Node<E> curNode = nodeAt(index - 1);
node.next = curNode.next;
curNode.next = node;
}
size++;
}
#Override
public void remove(int index) {
if(index == 0){
head = head.next;
}else{
Node<E> curNode = nodeAt(index - 1);
curNode.next = curNode.next.next;
}
}
#Override
public void set(int index, E value) {
nodeAt(index).data = value;
}
public String toString(){
String s = "";
Node<E> curNode = head;
s += curNode.data +" -> ";
while(curNode.next != null){
curNode = curNode.next;
s += curNode.data +" -> ";
}
s += "null";
return s;
}
#Override
public void clear()//Clears out the array object by setting everything to null
{
for(int i = 0; i < data.size; i++)
{
remove(0);
}
}
#Override
public int count()
{
int count = 0;
E temp;
for(int i = 0;i<size-1;i++)
{
if(get(i)!=null)
{
count++;
}
else
{
}
}
return count;
}
I am dealing with the following problem.
I have created a circular list, and i am also able to create x number of nodes for the number of people required in the circle. I am however stuck as i do not know how exactly i will iterate through the list for every nth person(node). I think i will need to create my own iterator but not sure how to go about it. I know it might be possible to import one from library but i don't want to do that as that will kill the learning process for me.
Here is the code for my Node Class
public class Node {
public int iData;
public Node next;
public Node(int x) {
iData = x;
}
public void displayNode() {
System.out.print(iData + " ");
}
}
Here is the code for Circular Linked List
public class CircularList {
private Node first;
private Node last;
private Node current;
private int count; // total items in the list
public CircularList getCurrent;
public CircularList() {
first = null;
last = null;
current = null;
count = 0;
}
public boolean isEmpty() {
return first == null;
}
public void step() {
current = current.next;
}
public Node getCurrent() {
return current;
}
public void insert(int x) {
Node newNode = new Node(x);
if (isEmpty()) {
first = newNode;
current = first;
} else {
current.next = newNode;
}
newNode.next = first;
last = newNode;
step();
count++;
}
public boolean search(int x) {
Node search = first;
int y = 0;
while (search.iData != x && y < count) {
search = search.next;
y++;
}
if (search.iData == x) {
System.out.println("Found the value: " + search.iData);
return true;
} else {
System.out.println("Value not found in list");
return false;
}
}
public void delete(int x) {
Node prev = first;
Node curr = first.next;
int y = 0;
while (y < count && curr.iData != x) {
prev = curr;
curr = curr.next;
}
if (count == 1) {
first = null;
count--;
} else {
prev.next = curr.next;
count--;
}
}
public void displayList() {
int x = 0;
Node printer = first;
while (x < count) {
printer.displayNode();
printer = printer.next;
x++;
}
}
}
Here is the code for my Josephus Class
public class Josephus {
private int numOfPeople; // number of people in a circle
private int countNum; // number used for counting off
CircularList circle;
public Josephus() {
circle = new CircularList();
numOfPeople = 0;
countNum = 0;
}
public void setNumOfPeople(int x) {
numOfPeople = x;
}
public int getNumOfPeople() {
return numOfPeople;
}
public void setCountNum(int x) {
countNum = x;
}
public int getcountNum() {
return countNum;
}
public void addPeople(int x) {
for (int i = 1; i < x; i++) {
circle.insert(i);
}
}
public void display() {
circle.displayList();
}
}
I need guidance in the right direction as to what i should do now. I do not ask for code or the answer. i want someone to push me towards the solutions. I can't go to sleep unless i solve this tonight.